我正在呼叫另一個庫中的函式,其回傳簽名定義如下:
(*studentlib.Student[StudentResponse], error)
Student定義為:
type Student[T any] struct {
st *students.Student
xyz *T
}
StudentResponse定義為:
type StudentResponse struct {
}
在我的方法簽名中,我將回傳型別定義如下:
func abc() (*studentlib.Student[StudentResponse], error) {
// do something here
}
但是對于函式回傳引數,我不斷收到如下錯誤:
missing ',' in parameter list
有人可以在這里幫忙嗎?代碼有什么問題?
uj5u.com熱心網友回復:
你用的是什么版本的圍棋?據我了解,泛型直到 1.18 版才可用。如果您使用的是 1.18 或更高版本,我首先會嘗試為您的 Student 結構賦予不同的名稱。從可讀性的角度來看,將多個結構命名為 Student 有點令人困惑。
進入這個問題,我認為最大的問題是你的“abc”函式無法知道它需要回傳什么泛型型別,因為它沒有接受引數。此外,您的“abc”函式需要在宣告中包含泛型型別。
幾個小問題。您的 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
}
如果你想在學生中使用 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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/474123.html
