GolangStudy/day4/type.go

42 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import "fmt"
// 一个类型声明语句创建了一个新的类型名称,和现有类型具有相同的底层结构。
// 新命名的类型提供了一个方法,用来分隔不同概念的类型,这样即使它们底层类型相同也是不兼容的。
// type 类型名字 底层类型
type Type1 int
// 类型声明语句一般出现在包一级,因此如果新创建的类型名字的首字符大写、
// 则在包外部也是可以使用的
// 声明了两种类型, Celsius 和 Fahrenheit 分别对应不同的温度单位,
// 他们虽然底层同属float64 但是他们属于不同的数据类型。
// 因此它们不可以被相互比较或混在一个表达式运算。
// 需要一个Celsius(T) 和 Fahrenheit(T)来显式的转换类型
// 注意: 可能会导致精度丢失
type Celsius float64 // 摄氏温度
type Fahrenheit float64 // 华氏温度
const (
AbsoluteZeroC Celsius = -273.15 // 绝对零度
FreezingC Celsius = 0 // 结冰点温度
BoilingC Celsius = 100 // 沸水温度
)
func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }
func main() {
fmt.Printf("%g\n", BoilingC-FreezingC) // "100" °C
boilingF := CToF(BoilingC)
fmt.Printf("%g\n", boilingF-CToF(FreezingC)) // "180" °F
//fmt.Printf("%g\n", boilingF-FreezingC)
//错误,类型不匹配 compile error: type mismatch
}