单个函数中的多个参数类型

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

Multiple argument type in single function

问题

我正在使用以下代码,并且我想要一个单一的函数来接受不同的结构体作为参数,并返回类型,并且在调用函数中使用该结构体的属性。如果在"FuncPassStruct"函数中使用switch语句,那么它可以工作,但是当我们从函数"findClassObj"返回时,它会给出编译错误"tmp.Name undefined (type interface {} is interface with no methods)"。如何实现这个?任何指针都可以。

package main

import "fmt"
import "reflect"

type MyClassFirst struct {
    Name string
}

type MyClassSecond struct {
    Name string
}

func main() {
    cls := MyClassFirst{Name: "Peter"}
    FuncPassStruct(cls)
}

func findClassObj(class interface{}) interface{} {
    switch v := class.(type) {
    default:
        fmt.Printf("unexpected type %T", v)
    case MyClassFirst:
        fmt.Printf("My first class....")
    case MyClassSecond:
        fmt.Printf("My second class....")
    }

    classStr := class.(MyClassFirst)
    return classStr
}

func FuncPassStruct(class interface{}) {
    fmt.Println("class =", reflect.TypeOf(class))

    switch v := class.(type) {
    default:
        fmt.Printf("unexpected type %T", v)
    case MyClassFirst:
        fmt.Printf("My first class....")
    case MyClassSecond:
        fmt.Printf("My second class....")
    }

    classStr := class.(MyClassFirst)
    fmt.Println("Name is: ----->", classStr.Name) // Working and print peter

    tmp := findClassObj(class)
    fmt.Println("From function: ------>", tmp.Name) // Giving compilation error
}

你可以尝试将以下代码替换到你的FuncPassStruct函数中,以解决编译错误:

tmp, ok := findClassObj(class).(MyClassFirst)
if ok {
    fmt.Println("From function: ------>", tmp.Name)
} else {
    fmt.Println("From function: ------>", tmp)
}

这样,如果findClassObj函数返回的是MyClassFirst类型的对象,就可以正确地访问tmp.Name属性。否则,将打印tmp的值。

英文:

I am using below code and i want single function to take the different struct as argument and return the type and use that struct attributes from calling function. If we use switch inside "FuncPassStruct" then it works but when we return from function "findClassObj", it gives compilation error as "tmp.Name undefined (type interface {} is interface with no methods)". How to achieve this ? Any pointer will be good.

package main

import "fmt"
import "reflect"

type MyClassFirst struct {
    Name string
}

type MyClassSecond struct {
    Name string
}

func main() {
    cls := MyClassFirst{Name: "Peter"}
    FuncPassStruct(cls)
}

func findClassObj(class interface{}) interface{} {

    switch v := class.(type) {
    default:
        fmt.Printf("unexpected type %T", v)
    case MyClassFirst:
        fmt.Printf("My first class....")
    case MyClassSecond:
        fmt.Printf("My second class....")
    }

    classStr := class.(MyClassFirst)
    return classStr
}

func FuncPassStruct(class interface{}) {
    fmt.Println("class = ", reflect.TypeOf(class))

    switch v := class.(type) {
    default:
        fmt.Printf("unexpected type %T", v)
    case MyClassFirst:
        fmt.Printf("My first class....")
    case MyClassSecond:
        fmt.Printf("My second class....")
    }

    classStr := class.(MyClassFirst)
    fmt.Println("Name is: -----> ", classStr.Name) ------> Working and print peter

    tmp := findClassObj(class)
    fmt.Println("From function: ------->", tmp.Name) ---> Giving compilation error
}

答案1

得分: 2

定义一个接口,其中包含一个获取名称的方法,并从两个类中实现该接口。如下所示,这样更加清晰。

package main

import (
	"fmt"
	"reflect"
)

type MyClass interface {
	GetName() string
}

type MyClassFirst struct {
	Name string
}

func (m MyClassFirst) GetName() string {
	return m.Name
}

type MyClassSecond struct {
	Name string
}

func (m MyClassSecond) GetName() string {
	return m.Name
}

func FuncPassStruct(class MyClass) {
	fmt.Println("class =", reflect.TypeOf(class))
	fmt.Println("Name is: ----->", class.GetName())
}

func main() {
	cls := MyClassFirst{Name: "Peter"}
	FuncPassStruct(cls)
}

结果:

class = main.MyClassFirst
Name is: -----> Peter
英文:

Define an interface with a method to get the name and implement that interface from the two classes. Its much cleaner as below.

package main

import (
	"fmt"
	"reflect"
)

type MyClass interface {
   GetName() string
}

type MyClassFirst struct {
    Name string
}

func (m MyClassFirst)GetName()string{
   return m.Name
}

type MyClassSecond struct {
    Name string
}

func (m MyClassSecond)GetName()string{
   return m.Name
}

func FuncPassStruct(class MyClass) {
    fmt.Println("class = ", reflect.TypeOf(class))
    fmt.Println("Name is: -----> ", class.GetName())
}

func main() {
    cls := MyClassFirst{Name: "Peter"}
    FuncPassStruct(cls)
}

result:

class =  main.MyClassFirst
Name is: ----->  Peter

答案2

得分: -2

你试图将 classStr := class.(MyClassFirst) 强制转换,但你的类可以是 MyClassFirstMyClassSecond,编译器无法正确进行转换。

英文:

You trying to cast classStr := class.(MyClassFirst) but your class can be MyClassFirst, or MyClassSecond compiler cannot cast it right

huangapple
  • 本文由 发表于 2021年7月20日 21:01:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/68455360.html
匿名

发表评论

匿名网友

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

确定