加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

白话Golang的Hello world

发布时间:2020-12-16 18:33:06 所属栏目:大数据 来源:网络整理
导读:####安装Golang开发环境 要想使用go语法做开发,首先当然是要搭建go的开发环境了。到Golang官网上下载go的安装包,找自己机器对应的版本。 当然如果你是在天朝,通常情况下被墙是不可避免的,你可以自行翻越或者到Golang中国上下载。 go在大中华地区还是很流

####安装Golang开发环境 要想使用go语法做开发,首先当然是要搭建go的开发环境了。到Golang官网上下载go的安装包,找自己机器对应的版本。 当然如果你是在天朝,通常情况下被墙是不可避免的,你可以自行翻越或者到Golang中国上下载。 go在大中华地区还是很流行的,可能跟围棋是中国发明的有关。

下载后找个顺眼的地方解压,比如/usr/local/go。进去到bin目录下执行go命令会得到如下信息:

go
Go is a tool for managing Go source code.

Usage:

	go command [arguments]

The commands are:

	build       compile packages and dependencies
	clean       remove object files
	doc         show documentation for package or symbol
	env         print Go environment information
	fix         run go tool fix on packages
	fmt         run gofmt on package sources
	generate    generate Go files by processing source
	get         download and install packages and dependencies
	install     compile and install packages and dependencies
	list        list packages
	run         compile and run Go program
	test        test packages
	tool        run specified go tool
	version     print Go version
	vet         run go tool vet on packages

Use "go help [command]" for more information about a command.

Additional help topics:

	c           calling between Go and C
	buildmode   description of build modes
	filetype    file types
	gopath      GOPATH environment variable
	environment environment variables
	importpath  import path syntax
	packages    description of package lists
	testflag    description of testing flags
	testfunc    description of testing functions

Use "go help [topic]" for more information about that topic.

诺,go开发环境你就按照好了,够傻瓜吧。

然而,这还不够。你一般会有一个自己写那些弱智代码的地方,称之为工作目录吧。在工作目录下怎么使用go呢? 这就需要把go这个命令放进环境变量,为了能完整的使用go来开发。我们需要定义一个GOROOT的环境变量,并将刚才这个bin目录放进path从而在任何地方都能使用go命令。 Linux下大概类似下面这样:

# vim /etc/profile

export GOROOT=/usr/local/go
export PATH=$PATH:$GOROOT/bin

# source /etc/profile

这样你就可以为所欲为地使用go这个命令了。

####指定GOPATH 不过,这还没完。go这么拽的语言当然要有点拽的姿势。除了GOROOT,还要定义一个GOPATH的环境变量,用来指定go项目源码和二进制文件的目录。 假设如此定义:

# vim /etc/profile

export $GOPATH=/workspace/golang:/data/go

# source /etc/profile

这里我们指定了两个GOPATH,/workspace/golang和/data/go,这样你就可以在GOPATH下执行类似

go get github.com/tools/godep

这样的命令来获取一个网上go开源项目了。上面的命令是获取godep这个包管理工具的源码并安装到GOPATH的bin目录下。

####Go项目目录结构 GOPATH下的目录结构通常为:

|--bin
|--pkg
|--src

bin存放编译后的可执行文件,pkg存放编译过程使用的包文件,src存放项目源文件。bin和pkg目录go会自动创建。

####Hello world 至此,我们可以操手来个hello world体味一下。在GOPATH的src目录下创建main.go文件:

package main

import "fmt"

func main() {
	fmt.Println("hello world")
}

代码格式自动格式化一下

go fmt main.go

哎呦,很叼噢,有木有!运行一下

go run main.go

世界都光明了。。。

####References The Go Programming Language

GOPATH 深度解析

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读