Monday, 15 March 2010

go - General slice type in golang? -



go - General slice type in golang? -

i'm having difficulties trying extend piece types general type in go. have created sample code explain problem. play ground version

package main import "fmt" type sequencer interface { mean() float64 } type sequence []int func (s sequence) mean() float64 { sum := 0.0 _, el := range s { sum += float64(el) } homecoming sum / float64(len(s)) } func main() { := []int{1, 2, 3, 4} b := sequence(a) fmt.println(b.mean()) fmt.println(b[:2].mean()) c := sequencer(b) fmt.println(c.mean()) fmt.println(c[:2].mean()) }

last line of main() function returns error saying variables of type sequencer cannot sliced:

cannot piece c (type sequencer)

is there way of defining general type of slices (int, float64, string,...) without hiding cool indexing capabilities of slices?

any type provides methods declared in interface definition can stored in interface variable of type. while actual value storing slice, type implement interface. , since in many cases impossible statically determine dynamic type of interface variable, language doesn't allow peek below covers without explicit type assertion.

if slicing expect types implementing sequencer type implement, simple solution extend interface include such method:

type sequencer interface { mean() float64 slice(start, end int) sequencer }

this can implemented sequence type in obvious way:

func (s sequence) slice(start, end int) sequencer { homecoming s[start:end] }

you can mean of piece using method:

fmt.println(c.slice(0, 2).mean())

you can experiment solution here: http://play.golang.org/p/umuqoarluu

types go slice

No comments:

Post a Comment