在 Golang 中使用泛型作为 return 类型时面临问题

Facing issue with having generic as return type in Golang

我正在调用另一个库的函数,其 return 签名定义如下:

(*studentlib.Student[StudentResponse], error)

Student 定义为:

type Student[T any] struct {
    st *students.Student
    xyz *T
}

StudentResponse 定义为:

type StudentResponse struct {
    
}

在我的方法签名中,我定义了 return 类型如下:

func abc() (*studentlib.Student[StudentResponse], error) {
   // do something here
}

但是对于函数 return 参数,我不断收到如下错误:

missing ',' in parameter list

有人可以帮忙吗?代码有什么问题?

您使用的是哪个版本的 go?据我了解,泛型直到 1.18 版才可用。如果您使用的是 1.18 或更高版本,我会首先尝试为您的 Student 结构提供不同的名称。从可读性的角度来看,将多个结构命名为 Student 有点令人困惑。

进入这个问题,我认为最大的问题是您的 'abc' 函数无法知道它 return 需要什么泛型类型,因为它没有参数。此外,您的 'abc' func 需要在声明中包含通用类型。

一些小问题。您的 StudentResponse 结构应该是一个接口。用“|”分隔要包含的特定数据类型字符

话虽如此,以下是让代码正常工作的方法:

package main

import (
    "fmt"
)

type Student[T any] struct {
    st string
    xyz T
}

type StudentResponse interface {
    int64 | float64
}

func main() {
    tmp1 := Student[int64]{ // will not throw an error. generic type is defined in StudentResponse
        st: "Testing",
        xyz: 15,
    }
    /*tmp2 := Student[string]{ // will throw an error if used in 'abc' func. generic type not defined in Student Response
        st: "Testing",
        xyz: "15",
    }*/
    
    resp, err := abc(&tmp1)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(resp)
}

func abc[T StudentResponse](s *Student[T]) (*Student[T], error) {
    // do something here
    err := fmt.Errorf("error: %s", "some error") // being used simply to have an error return value
    return s, err
 }

如果你想在 student 中使用 xyz 的指针,你可以这样做:

package main

import (
    "fmt"
)

type Student[T any] struct {
    st string
    xyz *T
}

type StudentInfo struct {
    Age float64
    Weight  int64
}

type StudentGrades struct {
    GPA float64
    CreditHours int64
}

type StudentResponse interface {
    StudentInfo | StudentGrades
}

func main() {
    info := StudentInfo{
        Age: 22.5,
        Weight: 135,
    }
    grades := StudentGrades{
        GPA: 3.6,
        CreditHours: 15,
    }
    tmp1 := Student[StudentInfo]{
        st: "tmp1",
        xyz: &info,
    }
    tmp2 := Student[StudentGrades]{
        st: "tmp2",
        xyz: &grades,
    }
    
    resp1, err1 := abc(&tmp1)
    if err1 != nil {
        fmt.Println(err1)
    }

    resp2, err2 := abc(&tmp2)
    if err2 != nil {
        fmt.Println(err2)
    }
    fmt.Println(resp1)
    fmt.Println(resp1.xyz)

    fmt.Println(resp2)
    fmt.Println(resp2.xyz)
}

func abc[T StudentResponse](s *Student[T]) (*Student[T], error) {
    // do something here
    err := fmt.Errorf("error: %s", "some error") // being used simply to have an error return value
    return s, err
 }