扩展未命名类型,例如 []string 的方法: Go:扩展未命名类型,例如 []string

huangapple go评论86阅读模式
英文:

Go: Extending unnamed types such as []string

问题

我在Go语言中对类型别名有些困惑。

我已经阅读了相关的Stack Overflow问题 - https://stackoverflow.com/questions/19334542/golang-why-can-i-type-alias-functions-and-use-them-without-casting

据我理解,如果底层结构相同,未命名类型和命名类型是可以互相赋值的。

我试图弄清楚的是,我是否可以通过为未命名类型命名来扩展它们 - 就像这样:

type Stack []string

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

这给我报错 cannot range over s (type *Stack)
尝试将其转换为 []string,但不起作用。

我知道下面的代码是可以工作的 - 这是我应该这样做的方式吗?如果是这样,我想知道为什么上面的代码不起作用,以及像 type Name []string 这样的声明有什么用处。

type Stack struct {
    data []string
}

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

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

I have read this related SO question - https://stackoverflow.com/questions/19334542/golang-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)
    }
}

答案1

得分: 7

你应该解引用指针s。

type Stack []string

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

You should dereference the pointer s

type Stack []string

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

huangapple
  • 本文由 发表于 2014年10月14日 15:54:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/26355488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定