英文:
List of strings and ints in go?
问题
我不知道我在做什么,所以决定尝试在Go中使用一个list (文档)。这是我能弄清楚的最多的内容:
- 为什么%v打印出
{0xf840024660 <nil> 0xf840023660 4}
? - 为什么我没有因为混合使用整数和字符串而得到错误?
- 如何强制指定类型?(例如只允许整数,只允许字符串等)
代码:
package main
import "fmt"
import "container/list"
func main() {
ls := list.New()
ls.PushBack("a")
ls.PushBack(4)
ls.PushBack("5")
fmt.Println(ls)
ls2 := list.New()
ls2.PushBack(4)
ls2.PushBack(8)
fmt.Printf("%v\naaa\n", *ls2.Front())
fmt.Println(*ls2.Back())
}
英文:
I have no idea what I am doing and I decided to try out using a list (docs) in go. This is the most I can figure out
- Why is %v printing
{0xf840024660 <nil> 0xf840023660 4}
? - Why am I not getting an error for mixing ints with strings?
- How do I force a type? (such as ints only, strings only etc)
Code:
package main
import "fmt"
import "container/list"
func main() {
ls := list.New()
ls.PushBack("a")
ls.PushBack(4)
ls.PushBack("5")
fmt.Println(ls)
ls2 := list.New()
ls2.PushBack(4)
ls2.PushBack(8)
fmt.Printf("%v\naaa\n", *ls2.Front())
fmt.Println(*ls2.Back())
}
答案1
得分: 38
首先,你可能不需要使用container/list
。你可能正在寻找类似切片和append()
的东西。例如:
x := []int { 1, 2, 3 }
x = append(x, 4)
x = append(x, 5, 6)
container/list
允许你混合使用不同类型的原因是它使用interface{}
来保存值,而任何类型都满足空接口。
英文:
First off, you probably don't want container/list
. You're probably looking for something like slices and append()
. For example:
x := []int { 1, 2, 3 }
x = append(x, 4)
x = append(x, 5, 6)
The reason container/list
lets you mix types is that it uses interface{}
to hold values, and any type satisfies the empty interface.
答案2
得分: 2
回答你关于调用Front()
和Back()
的第一个问题,是因为你打印的是Element
结构体,它不包含可打印的值。如果你想打印Element.Value
,你需要使用(*ls2.Front()).Value
。类似的原因也适用于为什么fmt.Println(ls)
打印出奇怪的结果。
英文:
To answer your first question for the calls to Front()
and Back()
, it is because you're printing out the Element
struct which does not contain printable values. If you want to print the Element.Value
you have to do (*ls2.Front()).Value
. Similar reasons are true for why fmt.Println(ls)
is printing weird.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论