Go Walk教程 - 流程式控制制(for)

來源:互聯網
上載者:User

標籤:range   列印   package   map   elb   item   https   replace   break   

Go的控制邏輯 for ,即可以用來迴圈讀取資料,又可以當作 while 來控制邏輯,還能迭代操作。

第一種,類似於C

sum := 0;for index:=0; index < 10 ; index++ {sum += index}

第二種,for 配合 range 可以用於讀取 slice 和 map 的資料,與一些語言的foreach類似:

for k,v:=range map {fmt.Println("map‘s key:",k)fmt.Println("map‘s val:",v)}

第三種,控制邏輯,代替了while的功能

sum := 1for sum < 1000 {sum += sum}

還有一個就是死迴圈,

i := 0for {if i > 10 {break}fmt.Println(i)i++}

用 break 終止當前迴圈

break 和 continue

 break 操作是跳出當前迴圈, continue 是跳過本次迴圈繼續下一個迴圈。

for i := 0 ; i < 10 ; i++ {if i > 5 {break ← 終止這個迴圈,只列印 0 到 5}println(i)}

利子:

// Copyright 2012 The Walk Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.package mainimport ("fmt""log""os""strings")import ("github.com/lxn/walk". "github.com/lxn/walk/declarative")func main() {mw := &MyMainWindow{model: NewEnvModel()}if _, err := (MainWindow{AssignTo: &mw.MainWindow,Title:    "Walk ListBox Example",MinSize:  Size{240, 320},Size:     Size{300, 400},Layout:   VBox{MarginsZero: true},Children: []Widget{VSplitter{Children: []Widget{ListBox{AssignTo: &mw.lb,Model:mw.model,OnCurrentIndexChanged: mw.lb_CurrentIndexChanged,OnItemActivated:mw.lb_ItemActivated,},TextEdit{AssignTo: &mw.te,ReadOnly: true,},},},},}.Run()); err != nil {log.Fatal(err)}}type MyMainWindow struct {*walk.MainWindowmodel *EnvModellb    *walk.ListBoxte    *walk.TextEdit}func (mw *MyMainWindow) lb_CurrentIndexChanged() {i := mw.lb.CurrentIndex()item := &mw.model.items[i]mw.te.SetText(item.value)fmt.Println("CurrentIndex: ", i)fmt.Println("CurrentEnvVarName: ", item.name)}func (mw *MyMainWindow) lb_ItemActivated() {value := mw.model.items[mw.lb.CurrentIndex()].valuewalk.MsgBox(mw, "Value", value, walk.MsgBoxIconInformation)}type EnvItem struct {name  stringvalue string}type EnvModel struct {walk.ListModelBaseitems []EnvItem}func NewEnvModel() *EnvModel {env := os.Environ()m := &EnvModel{items: make([]EnvItem, len(env))}for i, e := range env {j := strings.Index(e, "=")if j == 0 {continue}name := e[0:j]value := strings.Replace(e[j+1:], ";", "\r\n", -1)m.items[i] = EnvItem{name, value}}return m}func (m *EnvModel) ItemCount() int {return len(m.items)}func (m *EnvModel) Value(index int) interface{} {return m.items[index].name}

walk利子  

  

——

Go Walk教程 - 流程式控制制(for)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.