英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论