登录
首页 >  Golang >  Go问答

重用函数以确保其返回类型与在 Golang 中调用该函数的结构相匹配

来源:stackoverflow

时间:2024-03-23 17:45:30 326浏览 收藏

在 Go 语言中,可以使用泛型类型来实现类似 Java 中使用类型参数的情况。泛型函数可以通过指定其返回类型与调用它的结构体匹配的方式来定义,从而确保返回类型与结构体相匹配。这种方法可以简化代码,提高可读性和可维护性。

问题内容

我正在尝试在 golang 中做一些在 java 中使用 type 可以轻松完成的事情。例如:

public class myclass> {
    public type mymethod() {
        // do something
        return (type) this;
    }
}


public class test1 extends myclass {
    public string a;
    
    test1(string a) {
        this.a = a;
    }
}

public class test2 extends myclass {
    public string b;

    test2(string b) {
        this.b = b;
    }
}

所以,主要我可以做

test1 t1 = new test1("hello");
test2 t2 = new test2("world");
system.out.println(t1.mymethod().a); // prints "hello"
system.out.println(t2.mymethod().b); // prints "world"

我试图弄清楚是否有办法在 go 中做类似的事情。 也许是这样的:

type test1 struct {
    A string
}

type test2 struct {
    B string
}


func (val Type) MyMethod() Type {
    // Do something
    return val
}


func main() {
    t1 := test1{A: "hello"}
    t2 := test2{B: "world"}
    fmt.Println(t1.MyMethod().A) // Prints "hello"
    fmt.Println(t2.MyMethod().B) // Prints "world"
}

正确答案


感谢JimB,我找到了方法。

从 go 1.18 开始支持 Generic Types

所以 java myclass 在 go 中看起来像这样:

type mygeneric[t any] struct {
    self *t
}

func (val mygeneric[t]) mymethod() *t {
    // do something
    return val.self
}

java 类 test1 将是:

type test1 struct {
    mygeneric[test1]
    a string
}

func maketest1(a string) test1 {
    answer := test1{a: a}
    answer.self = &answer
    return answer
}

类似地,java 类 test2

type test2 struct {
    mygeneric[test2]
    b string
}

func maketest2(b string) test2 {
    answer := test2{b: b}
    answer.self = &answer
    return answer
}

所以 main 就是我们想要的

t1 := MakeTest1("hello")
t2 := MakeTest2("world")
fmt.Println(t1.MyMethod().A) // Prints "hello"
fmt.Println(t2.MyMethod().B) // Prints "world"

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《重用函数以确保其返回类型与在 Golang 中调用该函数的结构相匹配》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>