关于 Go 语言中 const 的问题

本问题来自《Go语言圣经》中 GIF 动画 中的代码,作用是生成一个利萨如图形 GIF。

代码如下:

// Lissajous generates GIF animations of random Lissajous figures.
package main

import (
    "fmt"
    "image"
    "image/color"
    "image/gif"
    "io"
    "math"
    "math/rand"
    "os"
    "reflect"
)

var palette = []color.Color{color.White, color.RGBA{0x6C, 0x9F, 0xB4, 0xff}}

const (
    whiteIndex = 0 // first color in palette
    greenIndex = 1 // second color in palette
)

func main() {
    lissajous(os.Stdout)
}

func lissajous(out io.Writer) {
    const (
        cycles  = 5     // number of complete x oscillator revolutions
        res     = 0.001 // angular resolution
        size    = 100   // image canvas covers [-size..+size]
        nframes = 64    // number of animation frames
        delay   = 8     // delay between frames in 10ms units
    )

    freq := rand.Float64() * 3.0 // relative frequency of y oscillator
    anim := gif.GIF{LoopCount: nframes}
    phase := 0.0 // phase difference
    for i := 0; i < nframes; i++ {
        rect := image.Rect(0, 0, 2*size+1, 2*size+1)
        img := image.NewPaletted(rect, palette)
        for t := 0.0; t < cycles*2*math.Pi; t += res {
            x := math.Sin(t)
            y := math.Sin(t*freq + phase)
            img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), greenIndex)
        }
        phase += 0.1
        anim.Delay = append(anim.Delay, delay)
        anim.Image = append(anim.Image, img)
    }

    // gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors

    fmt.Println(reflect.TypeOf(cycles))
}

不输出 gif,执行代码查看 cycles 的类型为 int.

% go run lissajous.go
int

将 cycles 的声明语句改为 var cycles = 5 后出错,这里 cycles 也是 int 型。

% go run lissajous.go
# command-line-arguments
./lissajous.go:44: constant 3.14159 truncated to integer
./lissajous.go:44: invalid operation: t < cycles * 2 * math.Pi (mismatched types float64 and int)

尝试改成 var cycles = 5.0 后,cycles 的类型为 float64,代码能正常运行。

问题

为什么用 const 声明的 intvar 声明的 int 会有差别?

查看回复