Wednesday, May 2, 2018

Go: Extending unnamed types such as []string



I am a bit confused in regards to type aliases in Go.



I have read this related SO question - Why can I type alias functions and use them without casting?.




As far as I understand, unnamed and named variables are assignable to each other if the underlying structure is the same.



What I am trying to figure out, is can I extend unnamed types by naming them - something like this:



type Stack []string

func (s *Stack) Print() {
for _, a := range s {
fmt.Println(a)

}
}


This gives me the error cannot range over s (type *Stack)
Tried casting it to []string, no go.



I know the below code works - is this the way I should do it? If so, I would love to know why the above is not working, and what is the use of declarations such as type Name []string.



type Stack struct {
data []string

}

func (s *Stack) Print() {
for _, a := range s.data {
fmt.Println(a)
}
}

Answer



You should dereference the pointer s




type Stack []string

func (s *Stack) Print() {
for _, a := range *s {
fmt.Println(a)
}
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...