goLang. call ".Front()" for a string list. But returns error saying string list has no Front method

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

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。

切片的元素范围从0len(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]++   
}

huangapple
  • 本文由 发表于 2014年5月16日 11:36:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/23692242.html
匿名

发表评论

匿名网友

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

确定