Go - Type Declarations


Named type
Format: type typeName underlying-type
A constructor with underlying-type value will exist without declaring
package main
import (
       "fmt"
)
// declare named type
// type name underlying-type
type C float64
type F float64
// declare constant by named type
const (
       FreezingC C = 0
       BoilingC  C = 100
)
// convert from C to F
func CToF(c C) F {
       return F(c*9/5 + 32)
}
func FToC(f F) C {
       return C((f - 32) * 5 / 9)
}
func main() {
       fmt.Printf("Freezing C:%g\n", FreezingC)
       fmt.Printf("Freezing F:%g\n", CToF(FreezingC))
       fmt.Printf("Boiling C:%g\n", BoilingC)
       fmt.Printf("Boiling F:%g\n", CToF(BoilingC))
}

Declare convert function in named type
format: func (variableName NamedType) funcName() {...}
package main
import (
       "fmt"
)
// declare named type
// type name underlying-type
type C float64
type F float64
// declare constant by named type
const (
       FreezingC C = 0
       BoilingC  C = 100
)
// convert from C to F
func (c C) CToF() F {
       return F(c*9/5 + 32)
}
func main() {
       fmt.Printf("Freezing C:%g\n", FreezingC)
       fmt.Printf("Freezing F:%g\n", FreezingC.CToF())
       fmt.Printf("Boiling C:%g\n", BoilingC)
       fmt.Printf("Boiling F:%g\n", BoilingC.CToF())
}
Comparasion
Named type can compare with underlying type.
Different named type can't be compared, will panic
package main
import (
       "fmt"
)
// declare named type
// type name underlying-type
type C float64
type F float64
func main() {
       fmt.Printf("%t\n", C(100) == C(100)) // true
       fmt.Printf("%t\n", C(100) == 100)    // true
       //     fmt.Printf("%t", C(100) == F(100)) // panic
}

panic
Define String() method in named type, this method will be called directly
Format: func (Named type) funcName namedType {..}
package main
import (
       "fmt"
)
// declare named type
// type name underlying-type
type C float64
type F float64
func (c C) String() string {
       return fmt.Sprintf("%g-C", c)
}
func main() {
       fmt.Printf("%s", C(23))
}



沒有留言:

張貼留言

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...