IT评测·应用市场-qidao123.com

标题: 【Go语言圣经2.5】 [打印本页]

作者: 惊落一身雪    时间: 昨天 23:37
标题: 【Go语言圣经2.5】
目标

了解类型界说不仅告诉编译器怎样在内存中存储和处置惩罚数据,还对步伐计划产生深远影响:

概念

要点

类型声明语句

  1. type 新类型名称 底层类型
复制代码
这条语句创建一个新的类型名称,其底层结构与现有类型雷同,但在类型体系中被以为是不同的。例如:
  1. type Celsius float64    // 摄氏温度类型
  2. type Fahrenheit float64 // 华氏温度类型
复制代码
纵然 Celsius 和 Fahrenheit 都基于 float64,它们是两个不同的类型,防止你无意中混用不同温度单位的数据。

类型转换操作

类型与方法

怎样界说 Celsius 与 Fahrenheit 两个定名类型及它们之间的转换和方法

  1. // Package tempconv performs Celsius and Fahrenheit temperature computations.
  2. package tempconv
  3. import "fmt"
  4. type Celsius float64    // 定义摄氏温度类型
  5. type Fahrenheit float64 // 定义华氏温度类型
  6. // 常量声明
  7. const (
  8.     AbsoluteZeroC Celsius = -273.15 // 绝对零度(摄氏)
  9.     FreezingC     Celsius = 0       // 冰点(摄氏)
  10.     BoilingC      Celsius = 100     // 沸点(摄氏)
  11. )
  12. // CToF 将摄氏温度转换为华氏温度
  13. func CToF(c Celsius) Fahrenheit {
  14.     return Fahrenheit(c*9/5 + 32)
  15. }
  16. // FToC 将华氏温度转换为摄氏温度
  17. func FToC(f Fahrenheit) Celsius {
  18.     return Celsius((f - 32) * 5 / 9)
  19. }
  20. // Celsius 的 String 方法,使其输出更友好
  21. func (c Celsius) String() string {
  22.     return fmt.Sprintf("%g°C", c)
  23. }
复制代码

类型比较与运算


总结


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4