英文:
Golang interface benefits
问题
我阅读了很多关于接口的内容,我认为我理解了它的工作原理。我阅读了关于interface{}
类型的内容,并将其用于函数参数。这一点很清楚。我的问题(以及我不理解的地方)是,如果我使用它,我会得到什么好处。可能我没有完全理解,但是例如我有以下代码:
package main
import (
"fmt"
)
func PrintAll(vals []interface{}) {
for _, val := range vals {
fmt.Println(val)
}
}
func main() {
names := []string{"stanley", "david", "oscar"}
vals := make([]interface{}, len(names))
for i, v := range names {
vals[i] = v
}
PrintAll(vals)
}
相比于以下代码,为什么它更好:
package main
import (
"fmt"
)
func PrintAll(vals []string) {
for _, val := range vals {
fmt.Println(val)
}
}
func main() {
names := []string{"stanley", "david", "oscar"}
PrintAll(names)
}
英文:
I read about the interfaces a lot and I think I understand how it works. I read about the interface{}
type and use it to take an argument of function. It is clear. My question (and what I don't understand) is what is my benefit if I am using it. It is possible I didn't get it entirely but for example I have this:
package main
import (
"fmt"
)
func PrintAll(vals []interface{}) {
for _, val := range vals {
fmt.Println(val)
}
}
func main() {
names := []string{"stanley", "david", "oscar"}
vals := make([]interface{}, len(names))
for i, v := range names {
vals[i] = v
}
PrintAll(vals)
}
Why is it better than this:
package main
import (
"fmt"
)
func PrintAll(vals []string) {
for _, val := range vals {
fmt.Println(val)
}
}
func main() {
names := []string{"stanley", "david", "oscar"}
PrintAll(names)
}
答案1
得分: 1
如果你总是想要打印string
值,那么第一种使用[]interface{}
的方法并不好,因为你会失去一些编译时的检查:如果你传递一个包含除了string
以外的值的切片,它不会警告你。
如果你想要打印除了string
以外的值,那么第二种使用[]string
的方法甚至无法编译通过。
例如,第一种方法也可以处理这种情况:
PrintAll([]interface{}{"one", 2, 3.3})
而第二种方法会给你一个编译时错误:
cannot use []interface {} literal (type []interface {}) as type []string in argument to PrintAll
第二种方法在编译时保证只有一个类型为[]string
的切片被传递;如果你尝试传递其他类型的值,将会导致编译时错误。
另请参阅相关问题:https://stackoverflow.com/questions/39092925/why-are-interfaces-needed-in-golang
英文:
If you're always want to print string
values, then the first using []interface{}
is not better at all, it's worse as you lose some compile-time checking: it won't warn you if you pass a slice which contains values other than string
s.
If you want to print values other than string
s, then the second with []string
wouldn't even compile.
For example the first also handles this:
PrintAll([]interface{}{"one", 2, 3.3})
While the 2nd would give you a compile-time error:
> cannot use []interface {} literal (type []interface {}) as type []string in argument to PrintAll
The 2nd gives you compile-time guarantee that only a slice of type []string
is passed; should you attempt to pass anything other will result in compile-time error.
Also see related question: https://stackoverflow.com/questions/39092925/why-are-interfaces-needed-in-golang
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论