Go Language Program Beginner

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Set up a working directory Go-examples to write the Go program with an absolute path of/home/go-examples. Start writing our first go program.

First, create a file under Go-work hello.go

Copy CodeThe code is as follows:
Hello.go
Package Main

Import "FMT"//Implement formatted I/O

/*printf someting*/
Func Main () {
Fmt. Printf ("hello,go!\n")
}

Let's Analyze This program:

1, the 2nd line of the program this is necessary. All go files start with package <something> and must be package main for standalone run files;

2. The 4th Line said that the "FMT" package should be added to main. Other packages that are not main are called libraries, and many other programming languages have similar concepts.

3, 1th and 4th lines//AND/*---*/are comments

4, the package main must appear first, followed by import. In go, the package always appears first, then import, then everything else. When the Go program executes, the function that is called First is Main.main (), which is inherited from C. This function is defined here;

5. Line 8th calls the function from the FMT package to print the string to the screen

Second, compile and run the code

Compile the source file and execute the resulting executable file

Copy CodeThe code is as follows:
[Root@localhost go-wrok]# Go Build hello.go
[Root@localhost go-work]# ls
Hello Hello.go
[Root@localhost go-work]#./hello
Hello,go!

With Go build plus the Go source file name to compile, we can get an executable file, by default the name of the file is the name of the source file removed. go suffix. Of course we can also use the-o option to specify a different name:

Copy CodeThe code is as follows:
[Root@localhost go-examples]# go build-o firstgo hello.go
[Root@localhost go-examples]# ls
Firstgo Hello.go

If we execute the go build command directly in the Go-examples directory, followed by a file name, we will get an executable with the same name as the directory name:

Copy CodeThe code is as follows:
[Root@localhost go-examples]# Go Build
[Root@localhost go-examples]# ls
Go-examples Hello.go

Iii. Program Entry points (entry point) and packages (package)

Go maintains the same style as the C-family language: The go source of the target executable must have a function called Main, which is the entry point for the executable. In addition, go adds a constraint: The main function as the entry point must be in the package named Main. As in the Hellogo.go source file above, the first line of the source code declares that the package that the file belongs to is main.

Go removes the concept of header files, and draws on the source organization of the package used by many mainstream languages. The package is a logical concept, with no one by one correspondence to the file. If more than one source file declares itself to belong to a package named Foo at the beginning, the code in these source files is logically subordinate to package Foo (these files are preferably in the same directory, at least the current go version cannot support the source files belonging to the same package in different directories).

We see Hellogo.go import a package named FMT and use the printf function within the package to output "Hello, go!". Intuition tells us that the FMT package appears to be a package in a standard library. Yes, the FMT package provides formatted text output and a related function to read formatted input, similar to printf or scanf in C. After we have imported the FMT package into our source file through the import statement, we can use the FMT package export function function (such as Printf).

In C, we use static to identify the local function or the global function. In go, the function in the package can be called externally, to see if the first parent of the function name is uppercase. This is a Go language curing convention: The first-uppercase function is considered an exported function, can be called by code outside the package, and a function that starts with a lowercase letter can only be used within the package. In the example you also see the printf function of the FMT package whose first parent is capitalized.

Iv. Gopath

Transform the hellogo.go above into two files: Main.go and Hello.go

Copy CodeThe code is as follows:
Hello.go
Package Hello

Import "FMT"

Func Hello (who string) {
Fmt. Printf ("hello,%s!\n", WHO)
}

Copy CodeThe code is as follows:
Main.go
Package Main

Import "Hello"

Func Main () {
Hello. Hello ("GO")
}

Compile main.go results with Go build as follows

Copy CodeThe code is as follows:
[Root@localhost go-examples]# Go Build main.go
Main.go:4:8:import "Hello": Cannot find Package

The compiler actually suggested that the package hello could not be found, while the package hello.go was clearly defined in the package. What's going on here? The way go compiler search package is different from our conventional understanding, go has a set of conventions in this respect, which involves an important environment variable: Gopath. We can use Go help Gopath to see the manual about Gopath.

The package search order for Go compiler is like this, as an example of searching for the Hello package:

* First, go compiler in the Go install directory (Goroot, here is/home/go/) to find out if there is src/pkg/hello related package source;

* If Export gopath=path1:paht2, go compiler will look for the presence of Path1/src/hello, Path2/src/hello ; the PATH1 and PATH2 configured in Gopath are called workplace;

* If the Hello package cannot be found in any of the above locations, an error is indicated.

In this case, we have not set the GOPATH environment variable, nor have we established a path like Path1/src/hello, so go compiler obviously can't find the Hello package. Let's set up the Gopath variable and create the relevant directory:

Copy CodeThe code is as follows:
[Root@localhost go-examples]# Export gopath=/home/go-examples/
[Root@localhost go-examples]# mkdir src/hello-p
[Root@localhost go-examples]# MV Hello.go src/hello/
[Root@localhost go-examples]# Go Build main.go
[Root@localhost go-examples]# ls
Main Main.go SRC
[Root@localhost go-examples]#./main
Hello,go!

Five, Go install

Move Main.go to Src/main, so this demo project looks more reasonable, all the source code is under SRC:

Copy CodeThe code is as follows:
[Root@localhost go-examples]# CD src/
[Root@localhost src]# ls
Hello Main.go

Go provides the install command, which, in contrast to the build command, installs the executable file or library file into the agreed directory after compiling the source. Let's take the main directory as an example:
Copy CodeThe code is as follows:
[Root@localhost src]# CD main/
[Root@localhost main]# Go Install

after the install command was executed, we found that there was no change in the main directory, and the main executable that was generated at the original build was missing. Don't worry, Go install has its own conventions:

* Go install (under Src/dir) the compiled executable file is named after its directory name (DIR)

* Go install installs the executable file in the bin directory with the SRC peer, and the bin directory is created automatically by go install

* Go install compiles the various package that the executable depends on and places it in the PKG directory at the same level as the SRC

Now let's take a look at the bin directory:

Copy CodeThe code is as follows:
[Root@localhost go-examples]# ls
Bin Pkg src
[Root@localhost go-examples]# ls bin/
Main

A bin directory does appear, and the program you just compiled is main under the bin.

Hello.go is not executable after compiling the main, and since main relies on the Hello package, the Hello is also associated with the compilation. This is the same as the result of executing the install separately in the Hello directory, let's try:

Copy CodeThe code is as follows:
[Root@localhost src]# CD hello/
[Root@localhost hello]# Go Install
[Root@localhost hello]# ls/home/go-examples/
Bin Pkg src

In our workspace (go-examples directory) There is a pkg directory, the pkg directory is a subdirectory named Linux_386, which has a file: Hello.a. This is the result of our install. The Hello.go is compiled into HELLO.A and installed into the pkg/linux_386 directory.

. A This suffix reminds us of a static shared library, but here. A is a unique file format for go, and is not compatible with traditional static shared libraries. But the designer of the Go language uses this suffix to look like this. A file also assumes the role of the "Static shared library" in the Go language. We might as well try to see if this hello.a can be treated as a "static shared library" by Go compiler. We remove the Hello directory from src and then execute go build in the main directory:

Copy CodeThe code is as follows:
[Root@localhost main]# Go Build
Main.go:4:8:import "Hello": Cannot find Package

Go compiler hint cannot find hello this package, the current version of the go compiler seems to ignore the. a file under Pkg. http://code.google.com/p/go/issues/detail?id=2775 This issue also confirms this, but subsequent go versions are likely to support link. a files. After all, we in the use of third-party package, it is likely to not get its source code, and in each project to save a third-party packages of the source code is also very detrimental to the project source of late maintenance.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.