Go 引入了新的令牌~。
~T 表示具有底層型別 T 的所有型別的集合
但是,我看不懂,請人幫忙解釋一下。
下面是一個例子。
type Ordered interface {
Integer | Float | ~string
}
uj5u.com熱心網友回復:
不僅有新的標記,還有介面的新語法。除了方法約束之外,您還可以宣告具有型別約束的介面。
為了滿足介面,型別必須同時滿足方法約束和型別約束。
從檔案:
一個介面,表示具有實作 String 方法的底層型別 int 的所有型別。
interface { ~int String() string }
對于具有“基礎型別”的型別int,這意味著該型別采用以下形式:
type SomeType int
為了滿足方法約束,必須宣告一個具有指定簽名的方法:
func (v SomeType) String() string {
return fmt.Sprintf("%d", v)
}
uj5u.com熱心網友回復:
在泛型提案中,~波浪號標記用于定義近似約束元素。泛型提案很好地解釋了它是什么而不涉及語言法律細節:
列出單一型別本身是沒有用的。為了滿足約束,我們希望能夠說的不僅僅是 int,而是“任何基礎型別為 int 的型別”。[...]如果程式使用
type MyString string,程式可以使用<帶有 type 值的運算子MyString。應該可以用 type 實體化 [a function]MyString。
如果您想要正式的參考,語言規范的提示版本已將基礎型別的定義放在其自己的部分中:
每個型別 T 都有一個基礎型別:如果 T 是預先宣告的布爾、數字或字串型別之一,或者是型別文字,則相應的基礎型別是 T 本身。否則,T 的基礎型別是T 在其型別宣告中參考的型別的基礎型別。
這涵蓋了型別文字和其他復合型別的非常常見的情況,您必須將識別符號系結到它們才能宣告方法:
type Foo struct {
n int
}
type ByteSlice []byte
或您在預先宣告的識別符號上定義的型別,泛型提案中就是這種情況:
type MyInt8 int8
type MyString string
實際含義是型別集只有精確元素的介面約束將不允許其他任何東西:
// hypothetical constraint without approximation elements
type ExactSigned interface {
int | int8 | int16 | int32 | int64
}
// CANNOT instantiate with MyInt8
func echoExact[T ExactSigned](t T) T { return t }
// constraints.Signed uses approximation elements e.g. ~int8
// CAN instantiate with MyInt8
func echo[T constraints.Signed](t T) T { return t }
與其他約束元素一樣,您可以在聯合中使用近似元素,例如在constraints.Signed帶有或不帶有句法糖的匿名約束中使用一個或多個元素:
// anonymous constraint
func echoFixedSize[T interface { ~int8 | ~int32 | ~int64 }](t T) T {
return t
}
// anonymous constraint with syntactic sugar
func echoFixedSizeSugar[T ~int8 | ~int32 | ~int64](t T) T {
return t
}
// anonymous constraint with syntactic sugar
func echoFixedSizeSugarOne[T ~int8](t T) T {
return t
}
近似元素的一個常見用例是需要具有方法的復合型別(切片、結構等)。在這種情況下,您必須系結識別符號:
// must bind identifier in order to declare methods
type ByteSeq []byte
func (b ByteSeq) DoSomething() {}
現在近似元素很方便允許實體化ByteSeq:
// ByteSeq not allowed, or must convert first
func foobar[T interface { []byte }](t T) { /* ... */ }
// ByteSeq allowed
func bazquux[T interface { ~[]byte }](t T) { /* ... */ }
注意:您不能將近似標記與型別引數一起使用:
// INVALID!
type AnyApprox[T any] interface {
~T
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422261.html
標籤:
