首页 > 代码库 > Go Walk教程 - 流程控制(for)

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

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 := 1
for sum < 1000 {
sum += sum
}

还有一个就是死循环,

i := 0
for {
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 main

import (
	"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.MainWindow
	model *EnvModel
	lb    *walk.ListBox
	te    *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()].value

	walk.MsgBox(mw, "Value", value, walk.MsgBoxIconInformation)
}

type EnvItem struct {
	name  string
	value string
}

type EnvModel struct {
	walk.ListModelBase
	items []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)