无法将GUI变量保持为全局

时间:2019-08-13 12:42:02

标签: user-interface go andlabs-ui

我发现以下代码有效:

// modified from: https://github.com/andlabs/ui/wiki/Getting-Started
package main
import ("github.com/andlabs/ui")
func makewinfn() {
    var name = ui.NewEntry()
    var button = ui.NewButton("Greet")
    var greeting = ui.NewLabel("")
    box := ui.NewVerticalBox()
    box.Append(ui.NewLabel("Enter your name:"), false)
    box.Append(name, false)
    box.Append(button, false)
    box.Append(greeting, false)
    mywindow := ui.NewWindow("MyTitle", 200, 100, false)
    mywindow.SetChild(box)
    button.OnClicked( func (*ui.Button) {greeting.SetText("Hello, " + name.Text() + "!") } )
    mywindow.OnClosing( func (*ui.Window) bool { ui.Quit(); return true } )
    mywindow.Show()
}
func main() {
    ui.Main(makewinfn)
}

但是,如果我尝试使用全局变量:

package main
import ("github.com/andlabs/ui")
// keeping following as global variables: 
var name = ui.NewEntry()
var button = ui.NewButton("Greet")
var greeting = ui.NewLabel("")
func makewinfn() {
    box := ui.NewVerticalBox()
    box.Append(ui.NewLabel("Enter your name:"), false)
    box.Append(name, false)
    box.Append(button, false)
    box.Append(greeting, false)
    mywindow := ui.NewWindow("MyTitle", 200, 100, false)
    mywindow.SetChild(box)
    button.OnClicked( func (*ui.Button) {greeting.SetText("Hello, " + name.Text() + "!") } )
    mywindow.OnClosing( func (*ui.Window) bool { ui.Quit(); return true } )
    mywindow.Show()
}
func main() {
    ui.Main(makewinfn)
}

此带有全局变量的代码可以编译,但是在运行时会产生以下错误:

fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x7fecb2712e19]

如何将GUI组件保留为全局变量?我将它们设置为全局,以便可以从其他功能访问它们。

1 个答案:

答案 0 :(得分:3)

在顶层(包块)使用变量时,将在开始执行 public IHttpActionResult CreateAgent([FromBody]AgentModel agentModel) { LogHelper.Info($"Creating agent {agentModel.Name}"); //Search if Agent name is in the system bool flgAgent = AgentsDataService.AgentExists(agentModel.Name); if (flgAgent == false) { var agentEntity = new Agent(); Mapper.DynamicMap(agentModel, agentEntity); var agentInformationEntities = Mapper.Map<IEnumerable<AgentInformation>>(agentModel.AgentInformations); agentEntity.AgentInformations = new EntitySet<AgentInformation>(); agentEntity.AgentInformations.AddRange(agentInformationEntities); var operationResult = AgentsDataService.InsertAgent(agentEntity); var result = Ok(new { Value = Mapper.Map<AgentModel>(operationResult) }); return result; }else { string resultWarning = $"Agent Name '{agentModel.Name}' is already used"; return Json(new { result = false, error = resultWarning }); //return BadRequest(resultWarning); } } 之前对它们进行初始化。

您从main()包中调用了代码,但是尚未调用其github.com/andlabs/ui,因此它可能依赖的ui.Main()包和资源尚未初始化。

仅声明变量,但尚未为其分配值,将其留给ui函数:

makewinfn()