我怎样才能将结果传递给go lang中的参数

ali*_*gur 11 go

我怎样才能将结果传递给go lang中的参数

有我的代码;

package main

import (
    "fmt"
)

type MyClass struct {
    Name string
}

func test(class interface{}) {
    fmt.Println(class.Name)
}

func main() {

    test(MyClass{Name: "Jhon"})
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到这样的错误

# command-line-arguments
/tmp/sandbox290239038/main.go:12: class.Name undefined (type interface {} has no field or method Name)
Run Code Online (Sandbox Code Playgroud)

有play.google.com 小提琴地址

eva*_*nal 20

您正在寻找;

func test(class MyClass) {
    fmt.Println(class.Name)
}
Run Code Online (Sandbox Code Playgroud)

就目前而言,该方法识别class为一些实现空接口的对象(意味着该范围内的字段和方法完全未知),这就是您得到错误的原因.

你的另一种选择是这样的;

func test(class interface{}) {
     if c, ok := class.(MyClass); ok { // type assert on it    
         fmt.Println(c.Name)
     }
}
Run Code Online (Sandbox Code Playgroud)

但是在你的例子中没有理由.只有你要进行类型切换或者有多个代码路径根据实际类型做不同的事情才有意义class.


ope*_*onk 8

根据您的需要,您(至少)有两个选择:

  1. 结构类型的方法
  2. 将struct类型作为参数的Func
package main

import "fmt"

type MyClass struct {
    Name string
}

func main() {
    cls := MyClass{Name: "Jhon"}

    // Both calls below produce same result
    cls.StructMethod()  // "Jhon"
    FuncPassStruct(cls) // "Jhon"
}

// Method on struct type
func (class MyClass) StructMethod() {
    fmt.Println(class.Name)
}

// Function that takes struct type as the parameter
func FuncPassStruct(class MyClass) {
    fmt.Println(class.Name)
}
Run Code Online (Sandbox Code Playgroud)

我相信其他人可能会提供一些我忘记的界面魔法.