windows开发一个go程序

如何在windows系统上开发go程序?直接进入正题。

Step 1

创建代码目录,我的是  E:\work\go\src\test 

编写代码一个main.go,一个add.go,存放方式为:

--test

      |--main.go

      |--add

             |---add.go

main.go代码如下:

package main

import (
	"fmt"
	"test/add"
)

func main() {
	var ret int = add.Add(1, 2)
	fmt.Printf("Hello, ret is %d", ret)

	var i int
	ch := make(chan int, 1)

	for {
		select {
		case ch <- 0:
		case ch <- 1:
		}
		i += <-ch
		fmt.Println("Value received:", i)
		if i > 10 {
			break
		}
	}

}

add.go代码如下:

package add

import "fmt"

func Add(a int, b int) (c int) {
	c = a + b
	fmt.Println(a, "+", b)
	fmt.Println("is:", c)

	return c
}


Step 2 设置环境变量

我的电脑-->右键-->属性-->高级系统设置-->环境变量,在“Administrator的用户变量“里找到 GOPATH,点击 编辑,修改成 e:\work\go ,点击确定。

Step 3 编译

点击  开始-->运行,输入cmd,进入E:\\work\go\src\test ,输入命令: go build -o main.exe test/

执行会在当前目录生成main.exe,执行main.exe 会打印如下:


E:\work\go\src\test>main.exe
1 + 2
is: 3
Hello, ret is 3Value received: 0
Value received: 0
Value received: 1
Value received: 2
Value received: 3
Value received: 3
Value received: 3
Value received: 3
Value received: 3
Value received: 4
Value received: 5
Value received: 6
Value received: 6
Value received: 7
Value received: 8
Value received: 9
Value received: 10
Value received: 10
Value received: 11

Step 4 总结

1、编译方式。我们的项目一般是main+若干个包、若干个文件组成,本文示例的方式可一句话编译整个工程。

2、包调用方式。自定义的包add,在main.go中调用时是这样:add.Add(1,2),不能这样调用Add(1,2),这是和本文的编译方式相关的,如果希望不带add包名,需要install add包到go的安装目录。

3、多次执行main.exe会发现“Value received X”打印的内容顺序不一定,此处是select多路复用机制的随机性体现。

 

 

 

你可能感兴趣的:(golang)