go3--常量和类型转换

/*
Go中不存在隐式转换,所有类型转换必须显式声明
转换只能发生在两种相互兼容的类型之间
类型转换的格式:
    <ValueA> [:]= <TypeOfValueA>(<ValueB>)


全局变量可以使用var()的形式,局部变量不可以使用var组的形式

type newInt int ,这里newInt不是int的别名,newInt转换成int类型的时候要显示的强制转化
*/

package main

import (
    "fmt"
    "strconv"
)

/*
    常量的值在编译时就已经确定,不能在运行时产生值,
    常量的定义格式与变量基本相同
    等号右侧必须是常量或者常量表达式
    常量表达式中的函数必须是内置函数
*/

/*
    在定义常量组时,如果不提供初始值,则表示将使用上行的表达式
    使用相同的表达式不代表具有相同的值
    iota是常量的计数器,从0开始,组中每定义1个常量自动递增1
    通过初始化规则与iota可以达到枚举的效果
    每遇到一个const关键字,iota就会重置为0
*/

const a int = 1
const b = 'A'

const (
    c = 1
    d = a + 1
    e = a + 2
)

const (
    c1 = 1
    d1
    e1        //不给产量赋值,则d1=c1,e1=d1,等于上面的值,
    _ABC = 89 //常量都是大写,前面加_就不会是public,
)

const (
    a, b = 1, "2"
    c, d
)

const a, b, c = 1, "2", "C"

func main() {
    var a float32 = 1.2
    b := int(a)
    fmt.Println(a) //1.2
    fmt.Println(b) //1

    var c bool = true
    d := int(c)
    fmt.Println(c) //
    fmt.Println(d) //cannot convert c (type bool) to type int

    /*
       string() 表示将数据转换成文本格式,因为计算机中存储的任何东西
       本质上都是数字,因此此函数自然地认为我们需要的是用数字65表示
       的文本 A。
    */

    var e int = 85
    f := string(e)
    fmt.Println(e)          //85
    fmt.Println(f)          //U,不能转成字符
    g := strconv.Itoa(e)    //int转成string
    h, _ := strconv.Atoi(g) //string转成int
    fmt.Println(g)          //"85"
    fmt.Println(h)          //85

}
package main

/*
运算符

Go中的运算符均是从左至右结合

优先级(从高到低)

^      !                                               (一元运算符)
*       /    %    <<    >>    &      &^
+      -     |      ^                                (二元运算符)
==   !=   <    <=    >=    >
<-     (专门用于channel)
&&       //前面是false后面不运算
||

*/
import (
    "fmt"
)

const a int = 1

func main() {
    fmt.Println(^2)            //-3,一元运算符
    fmt.Println(1 ^ 2)         //3,二元运算符
    fmt.Println(!true)         //false
    fmt.Println(1 << 10)       //1024,左移
    fmt.Println(1 << 10 << 10) //1048576
}
原文地址:https://www.cnblogs.com/yaowen/p/8066667.html