How do I write a function for multiple types in Golang?

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

How do I write a function for multiple types in Golang?

问题

我正在尝试编写一个辅助函数,可以接受不同的自定义类型作为输入,但我无法完全按照我想要的方式实现。以下是情况(顺便说一下,我正在构建一个返回实现HAL协议的JSON对象的API。这意味着资源和关系以链接的形式返回,而不仅仅是ID)。

我在应用程序中有许多模型,比如Student(学生)、Principal(校长)、School(学校)等等...
每个模型都有许多字段,有些相同,有些不同。理想情况下,我希望有一个函数可以迭代结构体的字段,并更改结构体中的另一个字段。最大的挑战是这些结构体可以是Student、Principal、School等类型。

模型:

type Person struct {
    halgo.Links
    Id        bson.ObjectId 
    Firstname string        
    Lastname  string        
    Email     string        
}

type Student struct {
    Person `bson:",inline"`

    School mgo.DBRef
}

type School struct {
    Id      bson.ObjectId
    Address []string     
    Name    string       
    Description string
}

然后,我希望有一个函数可以基本上接受任何这些结构体,使用reflect迭代字段,并对每个字段执行某些操作。

我尝试过一个接受interface{}类型的函数,但问题是你必须对参数进行类型断言才能访问任何字段。即使你做到了这一点,你仍然需要为每种类型/模型编写单独的函数:

func GenerateLinksHelper(m interface{}) {
...
}

最终,我试图找到一种方法来编写一个函数,它可以接受一个相对任意的结构体,并对可能存在的字段执行操作。

英文:

I'm trying to write a helper function that can take in different custom Types in Golang, but I can't figure out how to do it exactly the way I want. Here's the situation (incidentally, I'm building an API that returns JSON objects implementing HAL protocol. This just means that resources and relationships are returned as links and not simply ID').

I have a number of models in my app, such as Student, Principal, School, etc...
Each of these models has many fields, some same, some different. Ideally, I'd like a function that can iterate through the fields of a struct, and change another field in the struct. The big challenge is that these structs can be of type Student, Principal, School, etc...

Models:

type Person struct {
	halgo.Links
	Id        bson.ObjectId 
	Firstname string        
	Lastname  string        
	Email     string        
}

type Student struct {
	Person `bson:",inline"`

	School mgo.DBRef
}

type School struct {
	Id      bson.ObjectId
	Address []string     
	Name    string       
	Description string
}

Then, I'd like a function that can basically take any of these structs, iterate through the fields (using reflect), and do something with each field.

I've tried a function that takes interface{} but the problem is you have to type-assert the argument to have access to any of the fields. And even once you have that, you'll still have to write individual functions for each type/model anyways.:

func GenerateLinksHelper(m interface{}) {
...
}

Ultimately, I'm trying to find a way to write a function that takes in a somewhat arbitrary struct and perform operations on fields that may or may not be there.

答案1

得分: 4

我不确定你试图做什么,但是通过反射,你可以查看字段是否存在,然后对其进行操作。

以下是从《反射定律》文章(http://blog.golang.org/laws-of-reflection)中提取的示例。Playground链接:http://play.golang.org/p/neU3j2MYvz

package main

import (
	"fmt"
	"reflect"
)

type T1 struct {
	A int
	B string
}

type T2 struct {
	A int
}

func fct(i interface{}) {
	s := reflect.ValueOf(i).Elem()
	typeOfT := s.Type()
	for i := 0; i < s.NumField(); i++ {
		f := s.Field(i)
		if typeOfT.Field(i).Name == "B" {
			fmt.Printf("我是%s,我有一个字段B:%s\n", typeOfT.Name(), f.Interface())
		}
	}

}

func main() {
	t1 := T1{23, "skidoo"}
	t2 := T2{23}
	fct(&t1)
	fct(&t2)
}

希望对你有帮助!

英文:

I am not sure to understand what you are trying to do, but with reflection, you can see if a field exists or not and then do something with it.

Example derived from the 'laws of reflection' article (http://blog.golang.org/laws-of-reflection). Play: http://play.golang.org/p/neU3j2MYvz

package main

import (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

type T1 struct {
	A int
	B string
}

type T2 struct {
	A int
}

func fct(i interface{}) {
	s := reflect.ValueOf(i).Elem()
	typeOfT := s.Type()
	for i := 0; i &lt; s.NumField(); i++ {
		f := s.Field(i)
		if typeOfT.Field(i).Name == &quot;B&quot; {
			fmt.Printf(&quot;I am %s and I have a field B: %s\n&quot;, typeOfT.Name(), f.Interface())
		}
	}

}

func main() {
	t1 := T1{23, &quot;skidoo&quot;}
	t2 := T2{23}
	fct(&amp;t1)
	fct(&amp;t2)
}

huangapple
  • 本文由 发表于 2014年5月13日 05:05:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/23618867.html
匿名

发表评论

匿名网友

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

确定