在Go语言中,可以将结构体作为参数传递给函数。

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

golang, use structs as argument into a function

问题

请问你需要关于这个问题的建议。我刚开始学习golang,已经遇到了这个问题。

例如:

package main

import (
	"fmt"
)

type X struct{
	x string
}

type Y struct{
	y string
}

func main() {
	var x []X
	var y []Y
	
	f(x)
	f(y)
}

func f(value interface{}){
	if v, ok := value.([]X); ok {
		fmt.Println("this is X")
	}
	if v, ok := value.([]Y); ok {
		fmt.Println("this is Y")
	}
}

期望输出:this is X
this is Y

value interface{} 是错误的类型。我该如何将不同的结构体放入一个函数中,并动态定义其类型。是否有可能实现这样的功能?谢谢。

英文:

could you please advise on the question.
I just started to learn golang and have already choked with this situation.

For example:

package main

import (
	"fmt"
)
type X struct{
    x string
}
type Y struct{
	y string
}

func main() {
	var x []X
	var y []Y
	
	f(x)
	f(y)
}

func f(value interface{}){
	if(typeof(value) == "[]X"){
        fmt.Println("this is X")
    }
    if(typeof(value) == "[]Y"){
        fmt.Println("this is Y")
    }
}

expected output: this is X
                 this is Y

value interface{} is wrong type. How can I put different structures into one function and then dynamically define its type.

Is something like this possible?
Thanks.

答案1

得分: 4

你可以使用type switch来处理已知的确切类型。否则,你可以使用reflect包。

下面是使用类型切换方法的代码示例:

package main

import (
	"fmt"
)

type X struct {
	x string
}
type Y struct {
	y string
}

func main() {
	var x = []X{{"xx"}}
	var y = []Y{{"yy"}}

	f(x)
	f(y)
}

func f(value interface{}) {
	switch value := value.(type) {
	case []X:
		fmt.Println("这是 X", value)
	case []Y:
		fmt.Println("这是 Y", value)
	default:
		fmt.Println("这是 YoYo")
	}
}

播放链接:这里

英文:

You may use a type switch if you know the exact possible types. Otherwise you may use the reflect package.

Here is code demonstrating the type switch approach:

package main

import (
	"fmt"
)

type X struct {
	x string
}
type Y struct {
	y string
}

func main() {
	var x = []X{{"xx"}}
	var y = []Y{{"yy"}}

	f(x)
	f(y)
}

func f(value interface{}) {
	switch value := value.(type) {
	case []X:
		fmt.Println("This is X", value)
	case []Y:
		fmt.Println("This is Y", value)
	default:
		fmt.Println("This is YoYo")
	}
}

play link : here

huangapple
  • 本文由 发表于 2017年2月2日 03:27:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/41988041.html
匿名

发表评论

匿名网友

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

确定