sách gpt4 ăn đã đi

go - Tại sao tôi không thể thực hiện fmt.Sprintf("%d.%d.%d.%d", a...)?

In lại 作者:IT王子 更新时间:2023-10-29 01:17:26 30 4
mua khóa gpt4 giày nike

我正在学习 Go,而且我坚持使用 Go 之旅(exercise-stringer.go:https://tour.golang.org/methods/7)。

这是一些代码:

type IPAddr [4]byte  
// TODO: Add a "String() string" method to IPAddr.
func (a IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", a...)
}

所以我认为 IPAddr 的内部表示是 [4]byte,所以展开运算符有效。但我得到:

cannot use []string literal (type []string) as type []interface {} in argument to fmt.Sprintf

什么鬼? String slice 也不行,这是怎么回事?

biên tập:抱歉,我的问题中有一个错误 - 错误是关于类型 IPAddr,而不是 []sợi dây。我在玩代码,我粘贴了错误的输出。无论如何,感谢peterSO0x434D53关于 Go 中 slice 的不变性。

好吧,这引发了另一个问题。为什么要这样实现呢?我想您只需要一些 Iterable 接口(interface),因此实现它的任何结构都将“正常工作”。

旁注:当我第一次听说 Go 时,有这样一句大胆的声明“已编译,但富有表现力”。显式接口(interface)实现就是一个很好的例子,但是像显式转换、没有运算符重载等等给了我“90 年代 Java 的感觉”。这很可悲,因为 Go 似乎是一门很棒的语言。

câu trả lời hay nhất

A Tour of Go

Exercise: Stringers

Make the IPAddr type implement fmt.Stringer to print the address as a dotted quad.

For instance, IPAddr{1, 2, 3, 4} should print as "1.2.3.4".

gói chính

nhập khẩu "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.

hàm main() {
addrs := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for n, a := range addrs {
fmt.Printf("%v: %v\n", n, a)
}
}

没有从 []sợi dây đến []interface {} 的隐式转换。参见 Conversionshiện hữu The Go Programming Language Specification .您需要提供显式转换。例如,

gói chính

nhập khẩu "fmt"

type IPAddr [4]byte

// A "String() string" method for IPAddr.
func (a IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", a[0], a[1], a[2], a[3])
}

hàm main() {
addrs := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for n, a := range addrs {
fmt.Printf("%v: %v\n", n, a)
}
}

Đầu ra:

loopback: 127.0.0.1
googleDNS: 8.8.8.8

关于go - 为什么我不能执行 fmt.Sprintf ("%d.%d.%d.%d",一个...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33418107/

30 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress