在Go语言中,字符串和整数的列表可以使用以下方式表示:

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

List of strings and ints in go?

问题

我不知道我在做什么,所以决定尝试在Go中使用一个list (文档)。这是我能弄清楚的最多的内容:

  1. 为什么%v打印出{0xf840024660 <nil> 0xf840023660 4}
  2. 为什么我没有因为混合使用整数和字符串而得到错误?
  3. 如何强制指定类型?(例如只允许整数,只允许字符串等)

代码:

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

  1. Why is %v printing {0xf840024660 <nil> 0xf840023660 4}?
  2. Why am I not getting an error for mixing ints with strings?
  3. 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.

huangapple
  • 本文由 发表于 2013年4月16日 10:08:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/16027621.html
匿名

发表评论

匿名网友

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

确定