1 回答

TA貢獻1786條經驗 獲得超13個贊
語法foo(expr)where foois a type and expris a type conversion,如規范中所述:
轉化次數
轉換是形式為T(x)where Tis a type and x is an expression that can convert to type 的表達式T。
轉換 = 類型 "(" 表達式 [ "," ] ")" 。
如果類型以運算符*or開頭<-,或者類型以關鍵字開頭func且沒有結果列表,則必須在必要時將其括起來以避免歧義:
*Point(p) // same as *(Point(p))
(*Point)(p) // p is converted to *Point
<-chan int(c) // same as <-(chan int(c))
(<-chan int)(c) // c is converted to <-chan int
func()(x) // function signature func() x
(func())(x) // x is converted to func()
(func() int)(x) // x is converted to func() int
func() int(x) // x is converted to func() int (unambiguous)
在以下任何一種情況下,常量值x都可以轉換為類型T:
x可以用一個類型的值來表示T。
x是浮點常量,T是浮點類型,并且x可以T使用 IEEE 754 舍入到偶數規則舍入后由 type 的值表示。常數T(x)是四舍五入的值。
x是整數常量,T是字符串類型。x在這種情況下適用與非常量相同的規則。
轉換一個常量會產生一個類型化的常量作為結果。
uint(iota) // iota value of type uint
float32(2.718281828) // 2.718281828 of type float32
complex128(1) // 1.0 + 0.0i of type complex128
float32(0.49999999) // 0.5 of type float32
string('x') // "x" of type string
string(0x266c) // "?" of type string
MyString("foo" + "bar") // "foobar" of type MyString
string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant
(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
int(1.2) // illegal: 1.2 cannot be represented as an int
string(65.0) // illegal: 65.0 is not an integer constant
在以下任何一種情況下,非常量值 x 都可以轉換為類型 T:
x可分配給T。
x的類型并T具有相同的基礎類型。
x的類型并且T是未命名的指針類型,并且它們的指針基類型具有相同的底層類型。
x的類型并且T都是整數或浮點類型。x的類型 和T都是復雜類型。
x是一個整數或一個字節片或符文,并且T是一個字符串類型。
x是一個字符串,T是一個字節或符文的切片。
特定規則適用于數字類型之間或與字符串類型之間的(非常量)轉換。這些轉換可能會改變表示x并產生運行時成本。所有其他轉換僅更改類型,而不更改x.
沒有在指針和整數之間轉換的語言機制。包 unsafe 在受限情況下實現此功能。
有關更多詳細信息,請參閱鏈接頁面。
- 1 回答
- 0 關注
- 185 瀏覽
添加回答
舉報