Wednesday, 2 May 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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...