我是一个 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 浏览器中显示动态利沙如图形。 利萨如线颜色为黄色。
您需要使用命令行参数 web 启动应用 启动应用程序后,打开浏览器并将其指向 http://localhost:8000/
行 reference #3(func setColors(),代码示例结尾)应该设置黄色变量(line reference #2)。行引用 #3 是我收到“未命名字段初始化”编译器警告的地方。
当我按原样在 Intellij 中 运行应用程序时,没有设置 var yellow 并且没有在浏览器中正确绘制利沙如图形。
但是,如果我使用 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-idea 插件的 Intellij 中。然后这最近已修复,如您所见here .
关于variables - golang -- 初始化项目变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786653/
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到rubygems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决
我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击
我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是
我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘
我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R
我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc
假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit