Go Language Notes

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

This is my notes for go language while learning.

1. Return values:
The Go language designs using multi return values. The thing we must if the return value count is one, the return value's name can be omit or you must write th Em clearly.
Like this:
Func Test () error {
You can omit the variable name before error type.
But if it's like this you ' d better add the variable name:
Func test () (Result string, err error) {
}//Here I ignored the return statement
Another note, if the return values you don ' t need just use cables to receive them. If The return values don ' t have specified, the system would copy a default values for them.

2. Package declaration:
Every go source codes ' first line have a package declaration. The most important package name is main. This package name means the compiled the source codes, and there is a main entrance function, which is main function. The package must have a main to load the hole codes. Meanwhile there is a limit for main function, which is main function is not permit have parameters. There is a error if you don ' t use the package and you loaded.

3. Build and Installation:
While you build a project, you must set the environment variable Gopath.
The Gopath also set as your current work path. If My Go source code is in ~/golang/and then we should set the Gopath=~/golang. The specific method is:
Export Gopath=~/golang (remember besides the equal sign shouldn ' t add a space!)

4. Float32 and float64 calues compare:
Based my C language programming, compared with both float numbers you should better use the number 1e-7 or 1e7. But in go language, there is no many problems to compare, a float type, just use ' math ' package and isequal (NUM1, num2, P type) bool to compute.
Import "Math"
Func isequal (NUM1, num2, p float64) bool {
return Math. Abs (NUM1-NUM2) < P
}

5. Value Type
The go language formulate the array name is value type which is to say so if we make the array name as a parameter but AF ter the called the origin array ' values not changed. This is different with other language so, pay a attention in this character.

6. Return statement in if statement:
In go language programming, there are a difference between C and go, which is the return mustn ' t the end of the function in if Statement.
Func Test () {
If OK {
return True
} else {
return False
}//This statement can make errors during compile time.
}1. Timeout mechanism:

While we use the channel to communicate with other goroutines, it maybe occurred deadlock. Because the goroutine would wait for information to read or write. If There is no information to read and meanwhile there are no information to write to the channel, then the Read goroutines would wait forever. This is deadlock! So we should has a rule to avoid deadlock. Here we use SELECT statement to solve this problem.
We define a function to make a channel, it would run at any conditions.
Timeout: = Make (chan bool, 1)
Go func () {
Time. Sleep (1E9)
Timeout <-True
}
Select {
Case &LT;-CH:
//
Case <-timeout:
//
}
The SELECT statement would execute the statement randomly, so after 1 second the statement would execute the "<- Timeout "statement. Now we solved the deadlock in go language. It's very easy but it's the most effective method.

There is also another method to judge, the time is was out.
Select {
Case &LT;CH:
//
Case <-time. After (second * time. Second):
//
}



2. Multi-Core Parallel:

The go language provide the multi-core parallel computing. We can set the more CPU to help use compute. There is ways to implement the function.
A. We can declare a variable to keep the CPU number and then We distribute several works for every CPU core.
B. Also we can set the environment variable Gomaxprocs or set runtime. Gomaxprocs (CPUC) to the finish our works.

Give up the time slice rotation. If the process used much time, we can call the runtime. Gosched () function to give up the current process CPU time.


3. The global variable:

Yesterday, I met a problem that is I use ": =" To assign a value to a global variable. When I compile the source code, it appeared an error. I really don ' t why it made a error to me. While I used "var name =" XXXX ", it actually no errors. Just Now, I note so if you want to assign to a global variable and you must use the keyword "var". So everyone should know on that.


4. Command Line arguments:

We Use the package, flag to deal, the command line arguments. Firstly, we must use flag. Parse () Create a case. Second, we define some variables to storage the command line arguments like this:
var infile *string = flag. String ("I", "infile")
var outfile *string = flag. String ("O", "outfile")
In main function we must use flag. Parse (), then we can use the *infile and *outfile.


5. Operating File:

OS package. The OS package defines the Stdin, Stdout and Stderr. There is the declarations:
Stdin = NewFile (UIntPtr (syscall. Stdin), "/dev/stdin")
Stdout = NewFile (UIntPtr (syscall. Stdout), "/dev/stdout")
Stderr = NewFile (UIntPtr (syscall. Stderr), "/dev/stderr").
We know that the standard input or output is defines as the Devices/dev/stdin,/dev/stdout And/dev/stderr. Those device files is define in Linux or Unix OS.
The OS package defines those interfaces for developer:
Func (f *file) name () string/Get the File ' s name
Func (f *file) Read (b []byte) (n int, err error)
Func (f *file) Write (b []byte) (n int, err error)
Func (f *file) Seek (offset int64, whence int) (ret int64, err Error)
Func (f *file) WriteString (S string) (ret int, err error)
Func Mkdir (name string, perm FileMode) error/Make directory
Func Chdir (dir string) error//Change directory
Func Open (name string) (file *file, err Error)
Func Create (name string) (file *file, err Error)
We also can use OS. Stdout.wrtiestring (str []string) function writing the STR to the Stdout.

Others packages also has some functions to implement the functions. The Bufio and IO package also has those functions. Most of all, they is same.

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.