1 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
語法foo(expr)where foois a type and expris a type conversion,如規(guī)范中所述:
轉(zhuǎn)化次數(shù)
轉(zhuǎn)換是形式為T(x)where Tis a type and x is an expression that can convert to type 的表達(dá)式T。
轉(zhuǎn)換 = 類型 "(" 表達(dá)式 [ "," ] ")" 。
如果類型以運(yùn)算符*or開頭<-,或者類型以關(guān)鍵字開頭func且沒有結(jié)果列表,則必須在必要時(shí)將其括起來以避免歧義:
*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都可以轉(zhuǎn)換為類型T:
x可以用一個(gè)類型的值來表示T。
x是浮點(diǎn)常量,T是浮點(diǎn)類型,并且x可以T使用 IEEE 754 舍入到偶數(shù)規(guī)則舍入后由 type 的值表示。常數(shù)T(x)是四舍五入的值。
x是整數(shù)常量,T是字符串類型。x在這種情況下適用與非常量相同的規(guī)則。
轉(zhuǎn)換一個(gè)常量會(huì)產(chǎn)生一個(gè)類型化的常量作為結(jié)果。
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 都可以轉(zhuǎn)換為類型 T:
x可分配給T。
x的類型并T具有相同的基礎(chǔ)類型。
x的類型并且T是未命名的指針類型,并且它們的指針基類型具有相同的底層類型。
x的類型并且T都是整數(shù)或浮點(diǎn)類型。x的類型 和T都是復(fù)雜類型。
x是一個(gè)整數(shù)或一個(gè)字節(jié)片或符文,并且T是一個(gè)字符串類型。
x是一個(gè)字符串,T是一個(gè)字節(jié)或符文的切片。
特定規(guī)則適用于數(shù)字類型之間或與字符串類型之間的(非常量)轉(zhuǎn)換。這些轉(zhuǎn)換可能會(huì)改變表示x并產(chǎn)生運(yùn)行時(shí)成本。所有其他轉(zhuǎn)換僅更改類型,而不更改x.
沒有在指針和整數(shù)之間轉(zhuǎn)換的語言機(jī)制。包 unsafe 在受限情況下實(shí)現(xiàn)此功能。
有關(guān)更多詳細(xì)信息,請(qǐng)參閱鏈接頁面。
- 1 回答
- 0 關(guān)注
- 186 瀏覽
添加回答
舉報(bào)