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利子  

  

——

布局:

1、MainWindow

Layout:  

VBox{},垂直(vertical)

HBox{},水平(horizontal)

2、Splitter(分流器)

VSplitter,垂直(vertical)

HSplitter,水平(horizontal)

注:Layout作為MainWindow的一個屬性,而VSplitter、HSplitter作為一個獨立控件

3、Composite(組合),也是作為一個控件

他有一個Layout屬性,

Layout:Grid{Row:3,Columns: 2}//三行二列的網狀結構,如果是1行或1列可以省略Row或Columns

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM