@kjk1/

book slice filter

Go

No description

fork
loading
Files
  • main.go

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.47660037620483386","path":"main.go","file":{"path":"main.go","content":{"asEncoding":{"base64":"cGFja2FnZSBtYWluCgppbXBvcnQgImZtdCIKCmZ1bmMgZmlsdGVyRXZlblZhbHVlc0luUGxhY2UoYSBbXWludCkgW11pbnQgewoJLy8gY3JlYXRlIGEgemVyby1sZW5ndGggc2xpY2Ugd2l0aCB0aGUgc2FtZSB1bmRlcmx5aW5nIGFycmF5CglyZXMgOj0gYVs6MF0KCglmb3IgXywgdiA6PSByYW5nZSBhIHsKCQlpZiB2JTIgPT0gMCB7CgkJCS8vIGNvbGxlY3Qgb25seSB3YW50ZWQgdmFsdWVzCgkJCXJlcyA9IGFwcGVuZChyZXMsIHYpCgkJfQoJfQoJcmV0dXJuIHJlcwp9CgpmdW5jIG1haW4oKSB7CgkvLyA6c2hvdyBzdGFydAoJYSA6PSBbXWludHsxLCAyLCAzLCA0fQoJcmVzIDo9IGZpbHRlckV2ZW5WYWx1ZXNJblBsYWNlKGEpCglmbXQuUHJpbnRmKCIlI3ZcbiIsIHJlcykKCS8vIDpzaG93IGVuZAp9"},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import "fmt"

func filterEvenValuesInPlace(a []int) []int {
	// create a zero-length slice with the same underlying array
	res := a[:0]

	for _, v := range a {
		if v%2 == 0 {
			// collect only wanted values
			res = append(res, v)
		}
	}
	return res
}

func main() {
	// :show start
	a := []int{1, 2, 3, 4}
	res := filterEvenValuesInPlace(a)
	fmt.Printf("%#v\n", res)
	// :show end
}