Quick actions

cmd+k|ctrl+k

Navigation

Languages

Slices / Filter a slice / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-03-26T09:39:57Z

Updated

2019-03-26T09:39:57Z

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() {
	a := []int{1, 2, 3, 4}
	res := filterEvenValuesInPlace(a)
	fmt.Printf("%#v\n", res)
}
INFO