编写 Hello World

创建文件 hello.go,不写入任何内容。按照如下的命令尝试进行编译

$ go run hello.go

将会打印出如下错误:

package main:
hello.go:1:1: expected 'package', found 'EOF'

在Go语言中,所有文件必须隶属于某一个包。当前,只需要理解在文件的头部声明一个package name就可以了,其中package为关键字,name为你自己起的一个包名字。

在大型的程序中,包可以很好的有条理的组织各种功能。

例如,如果你想写一个关于交通工具的虚拟模型,你应该把所有属于car的模型放入一个叫做cars的包中,把所有属于bus的模型放入buses的包中。

组织相关的功能只是包的一种用途。

现在让我们在刚刚创建的hello.go文件中添加一条语句,之后重新执行运行命令

内容:

package main

执行后,会打印如下错误:

runtime.main_main·f: relocation target main.main not defined
runtime.main_main·f: undefined: "main.main"

Go程序启动时,需要在文件中有一个可标识入口。就像汽车必须有一把启动点火的钥匙、电脑需要有一个开机键,Go程序中需要有一个main函数。

在hello.go文件中添加另外一行,并且重试

内容:

package main

func main(){}

执行命令go run hello.go

程序正确执行,但是由于我们没有做任何其它操作,程序很快就退出了。

到目前为止,我们已经创建了自己的第一个程序。虽然没啥功能,但是已经可以正常运行了。

让我们继续添加一行

内容:

package main

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

运行,将会打印如下错误

./hello.go:4:2: undefined: Println

Println是向屏幕输入内容。执行命令之后,编译器报未定义。

为什么呢?

这里我们就需要用到包了。像Println这样的函数存放在某些包中。然而,当前这些包由于我们没有主动引入,但不能使用。如果我们需要使用这些包中的功能,首先需要import它们。

函数Println和其它读写文本和字符的函数,都存放在一个叫做fmt的包中——formatting的缩写。

我们再添加几行代码:

package main

import "fmt"

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

运行程序go run hello.go ,输出如下:

hello world

我们只是在package下面添加了一个import语句,第一个Go程序已经正常运行了。import之后,Println可以通过 包名.的方式进行调用。

Go语言 “ _ ”(下划线)

“_”是特殊标识符,用来忽略结果。

1.下划线在import中

   在Golang里,import的作用是导入其他package。

   import 下划线(如:import _ hello/imp)的作用:当导入一个包时,该包下的文件里所有init()函数都会被执行,然而,有些时候我们并不需要把整个包都导入进来,仅仅是是希望它执行init()函数而已。这个时候就可以使用 import _ 引用该包。即使用【import _ 包路径】只是引用该包,仅仅是为了调用init()函数,所以无法通过包名来调用包中的其他函数。

示例:

代码结构

src
|
+--- main.go
|
+--- hello
|
+--- hello.go

main.go

package main

import _ "./hello"

func main() {
// hello.Print()
//编译报错:./main.go:6:5: undefined: hello
}

hello.go

package hello

import "fmt"

func init() {
fmt.Println("imp-init() come here.")
} func Print() {
fmt.Println("Hello!")
}

输出结果:

imp-init() come here.

2.下划线在代码中

package main

import (
"os"
) func main() {
buf := make([]byte, 1024)
f, _ := os.Open("/Users/***/Desktop/text.txt")
defer f.Close()
for {
n, _ := f.Read(buf)
if n == 0 {
break }
os.Stdout.Write(buf[:n])
}
}

解释1:

下划线意思是忽略这个变量.

比如os.Open,返回值为*os.File,error

普通写法是f,err := os.Open("xxxxxxx")

如果此时不需要知道返回的错误值

就可以用f, _ := os.Open("xxxxxx")

如此则忽略了error变量

解释2:

占位符,意思是那个位置本应赋给某个值,但是咱们不需要这个值。
所以就把该值赋给下划线,意思是丢掉不要。
这样编译器可以更好的优化,任何类型的单个值都可以丢给下划线。
这种情况是占位用的,方法返回两个结果,而你只想要一个结果。
那另一个就用 "_" 占位,而如果用变量的话,不使用,编译器是会报错的。

补充:

import "database/sql"
import _ "github.com/go-sql-driver/mysql"

第二个import就是不直接使用mysql包,只是执行一下这个包的init函数,把mysql的驱动注册到sql包里,然后程序里就可以使用sql包来访问mysql数据库了。

运算符

全部运算符、分隔符,以及其他符号。

+ & += &= && == != ( )
- | -= |= || < <= [ ]
* ^ *= ^= <- > >= { }
/ << /= <<= ++ = := , ;
% >> %= >>= -- ! ... . :
&^ &^=

运算符结合律全部从左到右。

优先级 运算符 说明
high * / & << >> & &^
+ - | ^
== != < <= < >=
<- channel &&
low ||

简单位运算演 。

0110 &  1011 = 0010 	AND 都为 1。
0110 | 1011 = 1111 OR 少 个为 1。
0110 ^ 1011 = 1101 XOR 只能 个为 1。
0110 &^ 1011 = 0100 AND NOT 清除标志位。

标志位操作。

a := 0
a |= 1 << 2 // 0000100: 在 bit2 设置标志位。
a |= 1 << 6 // 1000100: 在 bit6 设置标志位
a = a &^ (1 << 6) // 0000100: 清除 bit6 标志位。

不支持运算符重载。尤其需要注意,"++"、"--" 是语句而非表达式。

 n := 0
p := &n // b := n++ // syntax error
// if n++ == 1 {} // syntax error
// ++n // syntax error n++
*p++ // (*p)++

没有 "~",取反运算也 "^"。

x := 1
x, ^x // 0001, -0010

Go命令

安装了go环境的话,你可以在命令行执行go命令查看相关的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
bug start a bug report
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 env用于打印Go语言的环境信息。

go run命令可以编译并运行命令源码文件。

go get可以根据要求和实际情况从互联网上下载或更新指定的代码包及其依赖包,并对它们进行编译和安装。

go build命令用于编译我们指定的源码文件或代码包以及它们的依赖包。

go install用于编译并安装指定的代码包及它们的依赖包。

go clean命令会删除掉执行其它命令时产生的一些文件和目录。

go doc命令可以打印附于Go语言程序实体上的文档。我们可以通过把程序实体的标识符作为该命令的参数来达到查看其文档的目的。

go test命令用于对Go语言编写的程序进行测试。

go list命令的作用是列出指定的代码包的信息。

go fix会把指定代码包的所有Go语言源码文件中的旧版本代码修正为新版本的代码。

go vet是一个用于检查Go语言源码中静态错误的简单工具。

go tool pprof命令来交互式的访问概要文件的内容。

标准命令详解

用户go get无法下载翻墙的时候的包,可以用gopm下载

什么是gopm

在nodejs中我们有npm,可以通过npm来下载安装一些依赖包。在go中也开发了类似的东西,那就是gopm。这玩意儿是七牛开发的。在这里说下,七牛公司大部分程序都是用go语言编写的,所以开发出这么一个方便的东西肯定也是合情合理的。

gopm 安装

go get github.com/gpmgo/gopm
go install github.com/gpmgo/gopm

通过这个命令来安装插件,默认的会存放到GOBIN,如果没有配置%GOBIN%环境变量,那么会默认安装到%GOPATH%下的bin目录,为了我们操作方便,我们把GOBIN加到%PATH%下。

使用说明

NAME:
Gopm - Go Package Manager USAGE:
Gopm [global options] command [command options] [arguments...] VERSION:
0.8.8.0307 Beta COMMANDS:
list list all dependencies of current project
gen generate a gopmfile for current Go project
get fetch remote package(s) and dependencies
bin download and link dependencies and build binary
config configure gopm settings
run link dependencies and go run
test link dependencies and go test
build link dependencies and go build
install link dependencies and go install
clean clean all temporary files
update check and update gopm resources including itself
help, h Shows a list of commands or help for one command GLOBAL OPTIONS:
--noterm, -n disable color output
--strict, -s strict mode
--debug, -d debug mode
--help, -h show help
--version, -v print the version

exmaple

gopm get -g -v -u golang.org/x/tools/cmd/goimports

通过gopm get xxx,可以将指定的包下载到gopm的本地仓库~/.gopm/repos(建议使用) 通过'gopm get -g xxx',可以将指定的包下载到GOPATH下。(建议使用) 通过'gopm get -l xxx',可以将指定的包下载到当前所在目录(不常用)

golang基础之第一个go程序的更多相关文章

  1. JAVA_SE基础——5.第一个Java程序HelloWorld&注释的应用

    配置完JDK&环境变量后,我们就可以开始写程序了,那么程序怎么写呢,用什么工具呢,我建议 为了方便学习,我们最好在一个磁盘下建立一个专门的文件来写java程序,比如就在D盘下建立一个名为&qu ...

  2. C#语言基础之第一个C#程序

    1.在记事本中编写如下代码,保存为Simple.cs文件. using System; class Hello World{ public static void Main(){ Console.Wr ...

  3. C#零基础入门-3-第一个控制台程序

    打开VS2017 文件 新建 项目 模板选择Visual C# Windows 控制台应用程序 快速写入Console.WriteLine 输入cw,然后快速按tab键两次即可.

  4. Python基础:第一个Python程序(2)

    1.Python Shell 1.1 Windows命令 (1)[开始]|[运行],输入cmd回车,进入Windows命令界面. (2)输入python,回车,进入Python Shell. 1.2 ...

  5. SpringMVC基础入门,创建一个HelloWorld程序

    ref:http://www.admin10000.com/document/6436.html 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要 ...

  6. 【云开发】10分钟零基础学会做一个快递查询微信小程序,快速掌握微信小程序开发技能(轮播图、API请求)

    大家好,我叫小秃僧 这次分享的是10分钟零基础学会做一个快递查询微信小程序,快速掌握开发微信小程序技能. 这篇文章偏基础,特别适合还没有开发过微信小程序的童鞋,一些概念和逻辑我会讲细一点,尽可能用图说 ...

  7. [置顶] 《Windows编程零基础》__2 一个完整的程序

    Windows开发的常识 1)窗口 Windows中最基本的概念也许就是窗口了,每一个前台程序都至少有一个窗口,一个窗口也是你可以看到的部分,比如,QQ有如下的登录窗口 基本上你在Windows中可见 ...

  8. Java基础---Java---网络编程---TCP的传输、客户端和服务端的互访、建立一个文本转换器、编写一个聊天程序

    演示TCP的传输的客户端和服务端的互访 需求:客户端给服务端发送数据,服务端收到后,给客户端反馈信息. 客户端: 1.建立Socket服务,指定要连接方朵和端口 2.获取Socket流中的输出流,将数 ...

  9. python基础学习(一) 第一个python程序

    1. 使用python/python3解释器的方式 按照惯例,我们都是以Hello world作为一门程序语言的开始,进行如下的操作: 在桌面上新建一个hello-python文件夹 进入hello- ...

随机推荐

  1. 【Linux命令】常用系统工作命令11个(echo、date、reboot、poweroff、wget、ps、top、pidof、kill、killall、pkill)

    目录 echo命令 date命令 reboot命令 poweroff命令 wget命令 ps命令 top命令 pidof命令 kill命令 killall命令 pkill命令 一.echo命令 ech ...

  2. CRF keras代码实现

    这份代码来自于苏剑林 # -*- coding:utf-8 -*- from keras.layers import Layer import keras.backend as K class CRF ...

  3. Android方法数超出限定的问题(multiDex,jumboMode)

    在Android项目开发中,项目代码量过大或通过引入很多jar导致代码量急剧增加,会出现错误: android.dex.DexIndexOverflowException: Cannot merge ...

  4. 点云3D 目标检测

    点云 点云是雷达采集到的信息. 关于点云基本介绍参考https://zhuanlan.zhihu.com/p/22581673 ros中的点云消息结构:http://docs.ros.org/jade ...

  5. 屏幕输入转换为int//方法大注释

    可以使用两种方法: using System; namespace 方法测试 { class Program { static void Main(string[] args) { Console.W ...

  6. .net 数据源DataSet 转换成模型

    /// <summary> /// DataSet转换成model 自动赋值返回集合 /// </summary> /// <typeparam name="T ...

  7. Python安装PyOpenGL

    1.目前PyOpenGL是用python2写的,如果你使用的是python3需要自己修改PyOpenGL,我这里使用的是python2.7 2.下载PyOpenGLhttps://pypi.org/p ...

  8. vue-列表动画

    实现列表动画 li { border: 1px dashed #999; margin: 5px; line-height: 35px; padding-left: 5px; font-size: 1 ...

  9. SQLserver创建用户和给用户权限(学)

    数据库基础知识:http://blog.csdn.net/u014600432/article/details/39645701 在SQL Server中创建用户角色及授权(使用SQL语句):http ...

  10. Day_02

    1.无参数无返回值函数的使用 package main import "fmt" //无参无返回值函数的定义 func MyFunc() { a := 666 fmt.Printl ...