英文:
goLang. call ".Front()" for a string list. But returns error saying string list has no Front method
问题
我有这样的代码:
t := strings.FieldsFunc(value, extract_word)
fmt.Println("t:", len(t), t)
m := make(map[string]int)
for word := t.Front(); word != nil; word = word.Next() {
m[word.Value.(string)]++
}
它报错了:
t.Front undefined (type []string has no field or method Front)
我知道列表有 Front()
方法。http://golang.org/pkg/container/list/ 但为什么在这里会报错呢?我很困惑,需要帮助。谢谢!
英文:
I have code like this
t := strings.FieldsFunc(value, extract_word)
fmt.Println("t:", len(t),t)
m := make(map[string]int)
for word := t.Front(); word != nil; word=word.Next(){
m[word]++
}
and it gets this error
t.Front undefined (type []string has no field or method Front)
I know list has Front() method.
http://golang.org/pkg/container/list/
but why it complains here?
so confused, need help.
thank you!
答案1
得分: 2
[]T
在其他语言(如Python)中被称为“列表”,但在Go语言中被称为“切片”http://golang.org/ref/spec#Slice_types。
切片的元素范围从0
到len(slice)-1
,可以使用类似C语言数组访问的方式来访问它们。通常认为切片的“前面”是slice[0]
,但如果你将切片用于实现类似栈的数据结构,你可以考虑不同的索引作为前面。
Go语言中没有任何内置类型定义了方法,但是有一些内置函数可以接受它们作为参数,比如len
函数。
你提到的包实现了List
类型。正如顶部的文档所说,“Package list实现了一个双向链表。”你可以通过调用list.New()
来创建这个双向链表,并且它具有Front
方法,以及包文档中列出的其他方法。
英文:
[]T
is not a "list" as it's referred to in other languages (e.g. Python). In Go, it's referred to as the "Slice" http://golang.org/ref/spec#Slice_types
Its elements range from 0
to len(slice)-1
, and are accessed with C-like array access notation. The "front" of the slice is generally considered slice[0]
, though you may consider a different index the front if you're using a slice to implement something like, e.g., a stack.
No built-in type in Go has any methods defined on it, but do have built-in functions that take them as arguments, such as len
.
The package you linked to implements the List
type. As the documentation at the top says "Package list implements a doubly linked list." This doubly linked list, which you can create by calling list.New()
, has a Front
method, among the others listed in the package documentation.
答案2
得分: 1
t
不是一个List
,它是一个字符串切片(切片和列表不是同一种东西)。切片的第一个元素是[0]
。
我认为你指的for
循环是这样的(未经测试):
for _, word := range t {
m[word]++
}
英文:
t
is not a List
. It is a slice of strings (slices and Lists are not the same thing). The first element of a slice is [0]
.
I believe the for
loop you mean is this (untested):
for _, word := range t {
m[word]++
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论