【问题标题】:golang -- Initializing Project Variablegolang -- 初始化项目变量
【发布时间】:2017-01-22 02:17:09
【问题描述】:

我是一个 golang 初学者,我有一个包级变量:

var yellow color.RGBA

我想在一个函数中初始化它,所以我这样做(没有编译器警告):

func setColors() {
    yellow = color.RGBA{R: 0xff, G: 0xff, B: 0x00, A: 0xff}
}

如果我在我的函数中执行此操作,我会收到“未命名字段初始化”编译器警告:

yellow = color.RGBA{0xff, 0xff, 0x00, 0xff}

但我的项目级变量允许我执行以下两项操作:

var yellow = color.RGBA{0xff, 0xff, 0x00, 0xff}
var yellow = color.RGBA{R: 0xff, G: 0xff, B: 0x00, A: 0xff}

为什么我可以在项目级初始化中省略字段名(R、G、B、A),而在函数中却不能?

1 月 24 日更新 -- 完整代码示例

这是我的变量初始化问题发生的地方。

此应用程序在网络浏览器中显示动态利萨如图形。 利萨如线颜色为黄色。

你需要用命令行参数web启动应用 启动应用后,打开浏览器并指向http://localhost:8000/

reference #3(func setColors(), end of code sample)应该设置黄色变量(line reference #2)。行参考 #3 是我得到“未命名字段初始化”编译器警告的地方。

当我从 Intellij 中按原样运行应用程序时,var yellow 没有设置,并且 lissajous 图形没有在浏览器中正确绘制。

但是,如果我使用行 reference #4 而不是 #3,则应用程序可以正常工作。

Line reference #1 工作正常,但我需要知道为什么 reference #3 不工作。

// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/

// Run with "web" command-line argument for web server.
// See page 13.

// Lissajous generates GIF animations of random Lissajous figures.

package main

import (
    "image"
    "image/color"
    "image/gif"
    "io"
    "math"
    "math/rand"
    "os"
    "time"
    "net/http"
    "log"
    "fmt"
    "reflect"
    "strconv"
)


var palette = []color.Color{color.Black, yellow }
var red color.RGBA= color.RGBA{0xff, 0x00, 0x00, 0xff}
var green color.RGBA = color.RGBA{0x00, 0xff, 0x00, 0xff}

// Line reference #1
//var yellow = color.RGBA{R: 0xff, G: 0xff, B: 0x00, A: 0xff}

// Line reference #2
var yellow color.RGBA

var blue color.RGBA = color.RGBA{0x00, 0x00, 0xff, 0xff}

const (

    whiteIndex = 0 // first color in palette
    yellowIndex = 1 // next color in palette
)

func main() {
    // The sequence of images is deterministic unless we seed
    // the pseudo-random number generator using the current time.
    // Thanks to Randall McPherson for pointing out the omission.
    rand.Seed(time.Now().UTC().UnixNano())
    setColors()
    if len(os.Args) > 1 && os.Args[1] == "web" {
        handler := func(w http.ResponseWriter, r *http.Request) {
            lissajous(w, r)
        }
        http.HandleFunc("/", handler)
        log.Fatal(http.ListenAndServe("localhost:8000", nil))
        return
    }
    lissajous(os.Stdout, nil)
}

func lissajous(out io.Writer,  r *http.Request) {
    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
    )
    // Get query parameters
    cycles  := getQueryParameterFloat("cycles", r, 5)
    size := getQueryParameterInteger("size", r, 100)
    sizeFloat := float64(size)
    nframes := getQueryParameterInteger("nframes", r, 64)
    delay := getQueryParameterInteger("delay", r, 8)

    fmt.Println("cycles type:", reflect.TypeOf(cycles))
    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*sizeFloat+0.5), size+int(y*sizeFloat+0.5),
                yellowIndex)
        }
        phase += 0.1
        anim.Delay = append(anim.Delay, delay)
        anim.Image = append(anim.Image, img)
    }
    gif.EncodeAll(out, &anim) // NOTE: ignoring encoding errors
}

// getQueryParameter returns the value of a parameter in the query string.
// If an error occurs, the function returns the default value passed in.
func getQueryParameterFloat(name string,  r *http.Request, defaultVal float64) float64 {


    v := r.URL.Query().Get(name)

    v2, err := strconv.ParseFloat(v, 64)
    if err != nil {
        return defaultVal
    } else {
        return v2
    }
}

func getQueryParameterInteger(name string, r *http.Request, defaultVal int) int {
    v := r.URL.Query().Get(name)

    v2, err := strconv.Atoi(v)
    if err != nil {
        return defaultVal
    } else {
        return v2
    }
}


func setColors() {
    // Line reference #3 When I use this, the application does not function correctly
    yellow = color.RGBA{0xff, 0xff, 0x00, 0xff}        

    // Line refernce #4 When I use this, the application **does** function correctly.
    //yellow = color.RGBA{R: 0xff, G: 0xff, B: 0x00, A: 0xff}

}

【问题讨论】:

  • 它为我编译。您能否发布一个显示问题的最小示例(即整个文件)?
  • Go Playground 为创建此类示例提供了一个不错的沙箱。例如:这是您所描述的工作示例play.golang.org/p/u6Vbm90SLP

标签: variables go initialization


【解决方案1】:

你从哪里得到这个错误?如果这是在带有 go-idea 插件的 Intellij 中。然后这个问题最近得到了修复,你可以看到here

【讨论】:

  • 是的,我正在使用带有 go-idea 插件的 Intellij。这可以解释为什么其他人可以运行代码而不会出错。我试图弄清楚如何按照其他人的要求将我的完整示例发布到 go playground(或者,将我的代码添加到我的原始帖子中)。
  • 您是否使用解决问题的相同版本的 intellij go 插件。?您可以查看我的答案以获取链接。
  • 插件版本为0.13.1924
【解决方案2】:

刚刚使用以下代码尝试了您的问题:

package main

import (
    "fmt"
    "image/color"
)

var yellow color.RGBA

func main() {
    fmt.Println(yellow)
    setColors()
    fmt.Println(yellow)
}

func setColors() {
    yellow = color.RGBA{R: 0xff, G: 0xff, B: 0x00, A: 0xff}
}

输出:

{0 0 0 0}
{255 255 0 255}

这似乎对我有用,我不确定我编写的代码是否与你的不同。

【讨论】:

  • @Andy Schweig 我已经用出现问题的完整应用程序更新了我的原始帖子,并附上了解释。我没有很好地解释我的问题。我在使用 yellow = color.RGBA{0xff, 0xff, 0x00, 0xff} 时遇到错误
猜你喜欢
  • 2016-07-18
  • 1970-01-01
  • 2019-01-11
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 2021-07-08
  • 2012-06-15
  • 2012-10-19
相关资源
最近更新 更多