Go语言笔记
This is my notes for go language while learning.
1. Return values:
The go language designs using multi return values. The thing we must take care are if the return value count is one, the return value's name can be omit or you must write
them clearly.
Like this:
func test() error {
} // in this case, you can omit the variable name before error type.
But if 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 will copy a default values for them.
2. Package declaration:
Every go source codes' first line has a package declaration. The most important package name is main. This package name means that after compiled the source codes, there
is a main entrance function that is main function. The package must has a main to load the hole codes. Meanwhile there is a limit for main function that is main function is not permit has parameters. There is an error if you don't use the package but 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/, 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 two float numbers you should better use the number 1e-7 or 1e7. But in go language, there are no many problems to compare
two 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 that is to say that if we make the array name as a parameter but after the called the origin array's values not changed.
This is different with other language so that pay a attention in this character.
6. return statement in if statement:
In go language programming, there is a difference between C and go, which is the return mustn't the end 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 channel to communicate with other goroutines, it maybe occurred deadlock. Because the goroutine will wait for information to read or write. If there is no information to read and meanwhile there is no information to write to the channel, then
the read goroutines will wait forever. This is deadlock! So we should have a rule to avoid deadlock. Here we use select statement to solve this problem.
// we define a function to make a channel, it will run at any conditions.
timeout := make(chan bool, 1)
go func() {
time.Sleep(1e9)
timeout <- true
}
select {
case <-ch:
//
case <-timeout:
//
}
The select statement will execute the two case statement randomly, so after 1 second the statement will execute the "<-timeout" statement. Now we solved the deadlock in go language. It is very easy but it is the most effective method.
There is also another method to judge the time is is out.
select {
case <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 are two ways to implement the function.
a. We can declare a variable to keep the CPU number, then we distribute several works for every CPU core.
b. Also we can set the environment variable GOMAXPROCS or set runtime.GOMAXPROCS(CPUc) to 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 was 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 an error to me. While I used "var name = "xxxx"", it actually no errors. Just now, I
note that if you want to assign to a global variable, you must use the keyword "var". So everyone should know about 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 are 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 are defines as the devices /dev/stdin, /dev/stdout and /dev/stderr. Those device files are 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 have some functions to implement the functions. The bufio and io package also have those functions. Most of all, they are same.
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。