gpt4 book ai didi

Golang 多态参数和返回

转载 作者:IT王子 更新时间:2023-10-29 01:37:08 24 4
gpt4 key购买 nike

假设我有函数:

func ToModelList(cats *[]*Cat) *[]*CatModel {
list := *cats
newModelList := []*CatModel{}
for i := range list {
obj := obj[i]
newModelList = append(newModelList, obj.ToModel())
}
return &newModelList
}

func ToModelList(dogs *[]*Dog) *[]*DogModel {
list := *dogs
newModelList := []*DogModel{}
for i := range list {
obj := obj[i]
newModelList = append(newModelList, obj.ToModel())
}
return &newModelList
}

有没有办法将这两者结合起来,这样我就可以做类似的事情

func ToModelList(objs *[]*interface{}) *[]*interface{} {
list := *objs
// figure out what type struct type objs/list are
newModelList := []*interface{}
// type cast newModelList to the correct array struct type
for i := range list {
obj := obj[i]
// type cast obj based on objs's type
newModelList = append(newModelList, obj.ToModel())
}
return &newModelList
}

最佳答案

首先,slice已经是一个引用,除非你需要改变slice本身,否则不需要将它作为一个指针来传递。其次,interface{} 可以是对象或指向对象的指针。您不需要 *interface{}。

我不确定你想要达到什么目的,但你可以这样做:

package main

// Interface for Cat, Dog
type Object interface {
ToModel() Model
}

// Interface for CatModel, DogModel
type Model interface {
Name() string
}

type Cat struct {
name string
}

func (c *Cat) ToModel() Model {
return &CatModel{
cat: c,
}
}

type CatModel struct {
cat *Cat
}

func (c *CatModel) Name() string {
return c.cat.name
}

type Dog struct {
name string
}

func (d *Dog) ToModel() Model {
return &DogModel{
dog: d,
}
}

type DogModel struct {
dog *Dog
}

func (d *DogModel) Name() string {
return d.dog.name
}

func ToModelList(objs []Object) []Model {
newModelList := []Model{}
for _, obj := range objs {
newModelList = append(newModelList, obj.ToModel())
}
return newModelList
}

func main() {
cats := []Object{
&Cat{name: "felix"},
&Cat{name: "leo"},
&Dog{name: "octave"},
}
modelList := ToModelList(cats)

for _, model := range modelList {
println(model.Name())
}
}

您为您的猫、狗等和您的模型定义接口(interface)。然后,您可以根据需要实现它们,执行 ToModelList() 非常简单。

关于Golang 多态参数和返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21636805/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com