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)
    }
}
3
  • 4
    Did you try for _, a := range *s ? Commented Oct 14, 2014 at 7: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. Commented Oct 14, 2014 at 8: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) Commented Oct 16, 2014 at 12:43

1 Answer 1

7

You should dereference the pointer s

type Stack []string

func (s *Stack) Print() {
    for _, a := range *s {
        fmt.Println(a)
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Francesc Campoy (Google) has a great presentation where he summarizes in which cases you can use *T or T and when it is different. speakerdeck.com/campoy/things-i-learned-teaching-go starting in page 38.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.