深入浅出golangGolang 入门资料+笔记Go

golang快速入门[8.4]-常量与隐式类型转换

2020-03-27  本文已影响0人  唯识相链2

前文

前言

const常量

常量声明

const untypedInteger = 12345
const untypedFloatingPoint = 3.141592
const typedInteger int           = 12345
const typedFloatingPoint float64 = 3.141592

常量的生存周期

    const k = 5
    address := &k

自动类型转换

var myInt =123

隐式整数类型转换

var myInt int = 123

var myInt int = 123.0

var myInt int = 123.1

隐式浮点类型转换

var myFloat float64 = 0.333

var myFloat float64 = 1

常量算术中的隐形转换

var answer = 3 * 0.333

const third = 1 / 3.0

const zero = 1 / 3

常量与具体类型的变量之间的算数转换规则

const b float64 = 1
const p = b * 2

const b int = 1
const p = b * 2.3

自定义类型的转换

type Numbers int8
const One Numbers = 1
const Two         = 2 * One

type Duration int64

const (
    Nanosecond Duration = 1
    Microsecond         = 1000 * Nanosecond
    Millisecond         = 1000 * Microsecond
    Second              = 1000 * Millisecond
)

package main

import (
    "fmt"
    "time"
)

const fiveSeconds = 5 * time.Second

func main() {
    now := time.Now()
    lessFiveNanoseconds := now.Add(-5)
    lessFiveSeconds := now.Add(-fiveSeconds)

    fmt.Printf("Now     : %v\n", now)
    fmt.Printf("Nano    : %v\n", lessFiveNanoseconds)
    fmt.Printf("Seconds : %v\n", lessFiveSeconds)
}

Output:
Now     : 2014-03-27 13:30:49.111038384 -0400 EDT
Nano    : 2014-03-27 13:30:49.111038379 -0400 EDT
Seconds : 2014-03-27 13:30:44.111038384 -0400 EDT

func (t Time) Add(d Duration) Time

var lessFiveNanoseconds = now.Add(-5)
var lessFiveMinutes = now.Add(-fiveSeconds)

var difference int = -5
var lessFiveNano = now.Add(difference)

Compiler Error:
./const.go:16: cannot use difference (type int) as type time.Duration in function argument

Add(time.Duration(difference))

编译时代码

// go/src/cmd/compile/internal/gc
func defaultlit2(l *Node, r *Node, force bool) (*Node, *Node) {
    if l.Type == nil || r.Type == nil {
        return l, r
    }
    if !l.Type.IsUntyped() {
        r = convlit(r, l.Type)
        return l, r
    }

    if !r.Type.IsUntyped() {
        l = convlit(l, r.Type)
        return l, r
    }

    if !force {
        return l, r
    }

    if l.Type.IsBoolean() {
        l = convlit(l, types.Types[TBOOL])
        r = convlit(r, types.Types[TBOOL])
    }

    lkind := idealkind(l)
    rkind := idealkind(r)
    if lkind == CTCPLX || rkind == CTCPLX {
        l = convlit(l, types.Types[TCOMPLEX128])
        r = convlit(r, types.Types[TCOMPLEX128])
        return l, r
    }

    if lkind == CTFLT || rkind == CTFLT {
        l = convlit(l, types.Types[TFLOAT64])
        r = convlit(r, types.Types[TFLOAT64])
        return l, r
    }

    if lkind == CTRUNE || rkind == CTRUNE {
        l = convlit(l, types.Runetype)
        r = convlit(r, types.Runetype)
        return l, r
    }

    l = convlit(l, types.Types[TINT])
    r = convlit(r, types.Types[TINT])

    return l, r
}

总结

参考资料

喜欢本文的朋友欢迎点赞分享~

image

唯识相链启用微信交流群(Go与区块链技术)

欢迎加微信:ywj2271840211

上一篇 下一篇

猜你喜欢

热点阅读