Go入门_一

· by 二三 · Read in about 2 min · (234 words)
Go

学习资料 http://docs.plhwin.com/gopl-zh/

A 开发环境搭建

0x1 安装GoSDK

Windows系统下载 https://storage.googleapis.com/golang/go1.8.3.windows-amd64.msi 需要翻墙。

0x2 本地环境变量配
GOBIN=C:\Go\bin          
GOROOT=C:\Go          
GOPATH=C:\GoWrokspaces      
PATH= ;C:\Go\bin;C:\GoWorkspaces\bin    

GoWorkspaces 目录下需要新建三个文件目录,分别是src,bin,pkg。

0x3 安装开发IDE

JetBrains Goglang https://www.jetbrains.com/go/
编辑go应用运行环境 github setting 设置应用运行main 文件 github setting

B 开发基础语法

0x1 函数参数的"值传递""引用传递"
type Emplyee struct {
	Name   string
	Age    int
	Status string
	Wallet int
}

func healthCheckup(emplyee Emplyee) {
	emplyee.Status = "Do Health Checkup"
	emplyee.Wallet=emplyee.Wallet-50
	fmt.Printf("%s 正在做体检 花费了50 还剩余额%d\n",emplyee.Name,emplyee.Wallet)
}
func financeRoom(emplyee *Emplyee)  {
	emplyee.Wallet=emplyee.Wallet+1000;
	fmt.Printf("%s 领取了工资 领取了1000 还剩余额%d\n",emplyee.Name,emplyee.Wallet)
}

func main() {
	var emp = Emplyee{Name: "larry", Age: 32, Status: "working",Wallet:100}
	fmt.Printf("员工做体检前 %v\n",emp)
	healthCheckup(emp)
	fmt.Printf("员工做体检后 %v\n",emp)

	fmt.Printf("员工领工资前 %v\n",emp)
	financeRoom(&emp)
	fmt.Printf("员工领工资后 %v\n",emp)

}

输出

员工做体检前 {larry 32 working 100}      
larry 正在做体检 花费了50 还剩余额50      
员工做体检后 {larry 32 working 100}      
员工领工资前 {larry 32 working 100}      
larry 领取了工资 领取了1000 还剩余额1100      
员工领工资后 {larry 32 working 1100}      
0x2 接口类型定义和实现类
// 定义Service接口,包含两个方法.
type Service interface {
	Sum(a, b int) (int, error)
	Concat(a, b string) (string, error)
}

// 返回实现Service接口的 basicService
func NewBasicService() Service {
	return basicService{}
}
//定义一个Service接口的实现结构体
type basicService struct{}

// 实现Service接口的Sum方法.   
func (s basicService) Sum(a, b int) (int, error) {
   ...
}

// 实现Service接口的Concat方法.
func (s basicService) Concat(a, b string) (string, error) {
   ...   
}

0x3 匿名函数
//greetingToWord 的参数为函数类型,参数名称_fGreeting 
func greetingToWord(_fGreeting func(whom string) string) string{
	word:=" word "
	return _fGreeting(word)
}

func greeting(whom string)string  {
	return "1 hello "+ whom
}

func main() {
	//传递greeting 函数
	someGreeting := greetingToWord(greeting)
	fmt.Println(someGreeting)

	//局部实现匿名函数
	someGreeting =greetingToWord(func(whom string) string {
		return "2 hello "+whom
	})
	fmt.Println(someGreeting)
	
}

输出:

1 hello  word      
2 hello  word