字符串列表 – golang

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

List of Strings - golang

问题

我正在尝试在golang中创建一个字符串列表。我查看了container/list包,但我不知道如何插入一个字符串。我尝试了几次,但没有结果。

我应该使用其他东西代替列表吗?
提前感谢。

编辑:不知道为什么你们给这个问题评负分....

英文:

I'm trying to make a list of Strings in golang. I'm looking up the package container/list but I don't know how to put in a string. I tried several times, but 0 result.

Should I use another thing instead of lists?
Thanks in advance.

edit: Don't know why are you rating this question with negatives votes...

答案1

得分: 3

修改您提供的示例,并将整数更改为字符串对我有效:

package main

import (
	"container/list"
	"fmt"
)

func main() {
	// 创建一个新的列表并放入一些字符串。
	l := list.New()
	e4 := l.PushBack("4")
	e1 := l.PushFront("1")
	l.InsertBefore("3", e4)
	l.InsertAfter("2", e1)

	// 遍历列表并打印其内容。
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Println(e.Value)
	}
}

请注意,我只是将代码翻译成中文,不会执行代码或提供任何其他功能。

英文:

Modifying the exact example you linked, and changing the ints to strings works for me:

package main

import (
	"container/list"
	"fmt"
)

func main() {
	// Create a new list and put some numbers in it.
	l := list.New()
	e4 := l.PushBack("4")
	e1 := l.PushFront("1")
	l.InsertBefore("3", e4)
	l.InsertAfter("2", e1)

	// Iterate through list and print its contents.
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Println(e.Value)
	}
}

答案2

得分: 1

如果你查看你提供的包的源代码,你会发现List类型保存了一个Element列表。观察Element,你会看到它有一个叫做Value的公开字段,它是一个interface{}类型,意味着它可以是任何类型:stringintfloat64io.Reader等等。

回答你的第二个问题,你会发现List有一个叫做Remove(e *Element)的方法。你可以像这样使用它:

fmt.Println(l.Len()) // 输出:4

// 遍历列表并打印其内容。
for e := l.Front(); e != nil; e = e.Next() {
	if e.Value == "4" {
		l.Remove(e) // 移除 "4"
	} else {
		fmt.Println(e.Value)
	}
}

fmt.Println(l.Len()) // 输出:3

总的来说,Golang的文档通常都很可靠,所以你应该首先查看文档。

https://golang.org/pkg/container/list/#Element

英文:

If you take a look at the source code to the package you linked, it seems that the List type holds a list of Elements. Looking at Element you'll see that it has one exported field called Value which is an interface{} type, meaning it could be literally anything: string, int, float64, io.Reader, etc.

To answer your second question, you'll see that List has a method called Remove(e *Element). You can use it like this:

fmt.Println(l.Len()) // prints: 4

// Iterate through list and print its contents.
for e := l.Front(); e != nil; e = e.Next() {
	if e.Value == "4" {
		l.Remove(e) // remove "4"
	} else {
		fmt.Println(e.Value)
	}
}

fmt.Println(l.Len()) // prints: 3

By and large, Golang documentation is usually pretty solid, so you should always check there first.

https://golang.org/pkg/container/list/#Element

huangapple
  • 本文由 发表于 2016年4月21日 00:13:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/36749542.html
匿名

发表评论

匿名网友

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

确定