如何将结构作为参数传递给函数? [英] How can I pass a struct to a function as parameter?
问题描述
如何传递结构以在golang中用作参数?有我的代码:
How can I pass a struct to function as a parameter in golang? There is my code:
package main
import (
"fmt"
)
type MyClass struct {
Name string
}
func test(class interface{}) {
fmt.Println(class.Name)
}
func main() {
test(MyClass{Name: "Jhon"})
}
当我运行它时,出现这样的错误
when I run it, I am getting an error like this
# command-line-arguments
/tmp/sandbox290239038/main.go:12: class.Name undefined (type interface {} has no field or method Name)
有play.golang.org 小提琴地址.
there is play.golang.org fiddle address.
推荐答案
您在寻找;
func test(class MyClass) {
fmt.Println(class.Name)
}
按目前的情况,该方法将 class
识别为实现空接口的某种对象(这意味着该域中的字段和方法是完全未知的),这就是您收到错误的原因.
As it stands the method recognizes class
as some object which implements the empty interface (meaning in that scope it's fields and methods are completely unknown) which is why you get the error.
您的其他选择是这样的
func test(class interface{}) {
if c, ok := class.(MyClass); ok { // type assert on it
fmt.Println(c.Name)
}
}
但是在您的示例中没有理由.仅当您要进行类型切换或具有多个根据 class
的实际类型执行不同操作的代码路径时,这才有意义.
But there is no reason to in your example. It only makes sense if you're going to do a type switch or have multiple code paths that do different things based on the actual type of class
.
这篇关于如何将结构作为参数传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!