zoukankan      html  css  js  c++  java
  • golang基础之第一个go程序

    编写 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',可以将指定的包下载到当前所在目录(不常用)

  • 相关阅读:
    Codeforces D
    Codeforces C
    Minimal Ratio Tree HDU
    Tian Ji -- The Horse Racing HDU
    Monkey Banana Problem LightOJ
    Rooks LightOJ
    洛谷 P2742 [USACO5.1]圈奶牛Fencing the Cows || 凸包模板
    洛谷 P3382 【模板】三分法
    洛谷 P1438 无聊的数列
    洛谷 P1082 同余方程
  • 原文地址:https://www.cnblogs.com/guigujun/p/10877281.html
Copyright © 2011-2022 走看看