ex-常量

 未定义类型常量和已定义类型常量

constant  a = 123

等式左边已命名常量,右边是未命名常量,拥有未定义的类型。当有足够的内存来存储整数值时,可以始终精确地表示整数

未命名常量只会在编译期间存在,因此其不会存储在内存中,而命名常量存在于内存静态只读区,不能被,Go语言禁止了对常量取地址的操作

// Constants live within the compiler.
	// They have a parallel type system.
	// Compiler can perform implicit conversions of untyped constants.

	// Untyped Constants.
	const ui = 12345    // kind: integer
	const uf = 3.141592 // kind: floating-point

	// Typed Constants still use the constant type system but their precision
	// is restricted.
	const ti int = 12345        // type: int64
	const tf float64 = 3.141592 // type: float64
    const uia int16 =12345  // type:int16 整数隐式类型装换
	// ./constants.go:14: constant 1000 overflows uint8
	// const myUint8 uint8 = 1000

	// Constant arithmetic supports different kinds.
	// Kind Promotion is used to determine kind in these scenarios.
	// Variable answer will be implicitly converted to type floating point.
	var answer = 3 * 0.333 // KindInt(3) * KindFloat(0.333)

	// Variable third will be of kind floating point.
	const third = 1 / 3.0 // KindInt(1) / KindFloat(3.0)

	// Variable zero will be of kind integer.
	const zero = 1 / 3 // KindInt(1) / KindInt(3)

	// This is an example of constant arithmetic between typed and
	// untyped constants. Must have like types to perform math.
	const one int8 = 1
	const two = 2 * one // KindInt(2) * int8(1)

隐式类型转换:必须要有untype constant

在Go语言中,变量之间没有隐式类型转换,不同的类型之间只能强制转换。但是,编译器可以进行变量和常量之间的隐式类型转换。只要不需要截断,就可以将类型为整数的未命名常量隐式转换为有符号和无符号命名常量

var a int8 = 234;   

常量运算中隐式转换:

Go语言规范中运算符的规则。该规则规定,除非操作涉及位运算或未定义的常量,否则操作数两边的类型必须相同。这意味着常量在进行运算时,操作数两边的类型不一定相同

在Go语言规范中,对于常量表达式也制定了专门的规则。除了移位操作,如果操作数两边是不同类型的无类型常量,则结果类型的优先级为:整数(int)<符文数(rune)<浮点数(float)<复数(Imag) 

常量与具体类型的变量之间的运算:常量与具体类型的变量之间的运算,会使用已有的具体类型

type conversion

强制转换需要满足如下任一条件:(x是非常量类型的变量,T是要转换的类型)

1. x可以直接复制给T类型变量

2. x的类型和T具有相同的底层类型

3. x的类型和T都是未命令的指针类型,并且指针指向的类型具有相同的底层类型

4. x的类型和T都是整型,或都是浮点型,或者都是复数类型

5. x是整数值 或[]byte类型的值,T是string类型

6. x是一个字符串,T是[]byte或 []rune

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值