From c87729bc95f866bf65232eee1a4efc586c6b14e7 Mon Sep 17 00:00:00 2001 From: dugulingping Date: Sun, 6 Nov 2022 15:01:29 +0800 Subject: [PATCH] =?UTF-8?q?day4=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day4/type.go | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 day4/type.go diff --git a/day4/type.go b/day4/type.go new file mode 100644 index 0000000..7842603 --- /dev/null +++ b/day4/type.go @@ -0,0 +1,41 @@ +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 + +}