2

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)
    }
}
Community
  • 1
  • 1
DannyB
  • 12,810
  • 5
  • 55
  • 65
  • 4
    Did you try `for _, a := range *s` ? – fuz Oct 14 '14 at 07:59
  • 3
    `s` is a pointer to `Stack` and thus a pointer to `[]string` and in Go you cannot range over pointers. A `range *s` would do. This has nothing to do with "named" or "unnamed" types or aliases, it is just a result of static typing and your s having the wrong type for range-ing. – Volker Oct 14 '14 at 08:01
  • **In Go, there is no such thing as a type alias.** The `type` keyword introduces new named types. They are not aliases. (This is one of Go's important strengths compared to various other languages) – Rick-777 Oct 16 '14 at 12:43

1 Answers1

7

You should dereference the pointer s

type Stack []string

func (s *Stack) Print() {
    for _, a := range *s {
        fmt.Println(a)
    }
}
Jarod
  • 1,662
  • 1
  • 11
  • 19
  • Excellent! So simple. For some reason, I looked for the complicated solution. I guess it is because the Go compiler spoiled me - it usually lets me know when `*type` is used as `type`. Thanks a lot. – DannyB Oct 14 '14 at 08:38
  • Francesc Campoy (Google) has a great presentation where he summarizes in which cases you can use *T or T and when it is different. https://speakerdeck.com/campoy/things-i-learned-teaching-go starting in page 38. – siritinga Oct 14 '14 at 11:22