Golang--10 things you don't know

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

The translation of this article from the article, here to express our thanks

Ten things You (probably) don ' t know about Golang

anonymous struct (Anonymous structs)

Template data

struct {    string    //猜测 User 是一个接口,接口指针的切片} {    title,    USERS,}err := tmpl.Execute(w, data)

(cheaper and safer than using map[string]interface{})
I don't really understand, what does that mean?

Embedded lock (Embedded Lock)

varstruct{    sync.Mutex   //匿名对象的方法,(类似于一种继承的方式)    int}hits.Lock()  // (和C++中的继承很类似)hits.n++hits.Unlock()

Nested structs Nested structure

Decoding deeply nested JSON data

{"data ": {"children ": [{"data ": {"title ":  "the Go homepage"  , "url " :  "http://golang.org/"  } }, ...] } }
typestruct{    Titel  string    URL    string}typestruct{  //使用 Structs 来表示 Json 数据,十分巧妙    struct {        Children []struct {            Data Item        }    }}记得在 golang的 json 库中,既可以直接使用这样的结构来进行 JSON 数据的解析和发送。

Command-Line godoc command line Godoc

//这里 godoc 是命令,sync是包名, Mutex是类型名

The displayed values are as follows

Type Mutex struct {
Contains filtered or unexported fields}
A Mutex is a mutual exclusion lock. Mutexes can created as part of
other structures; The zero value for a mutex was an unlocked mutex.

Func (M *mutex) Lock ()
Lock locks M. If the lock is already on use, the calling Goroutine
Blocks until the mutex is available.

Func (M *mutex) Unlock ()
Unlock unlocks M. It is a run-time error if m isn't locked on entry to

A locked Mutex is not associated with a particular goroutine. It isallowed for one goroutine to lock a Mutex and then arrange for anothergoroutine to unlock it.

GODC-SRC can display the source code of Golang directly

% godoc -src sync Mutex

Shown below:

A Mutex is a mutual exclusion lock. Mutexes can created as
Part of other structures//the zero value for a Mutex was an unlocked
Mutex. Type Mutex struct {
State int32
Sema UInt32}//Local per-p Pool Appendix. Type poollocal struct {
Mutex//Protects shared.
Contains filtered or unexported fields}

You can see that it shows the unexported state! Allows us to explore the source code in depth.

Mock out the file system (imitate filesystem)

Now there is a package that needs to collaborate with the file system, but you don't want your test to use a real disk, what should I do?

varFS FileSystem = osfs{}typeFileSystemInterface{//should be the interface of the file system in the standard libraryOpen (namestring) (file, error) Stat (namestring) (Os.fileinfo, error)}typeFileInterface{//interface of file in standard libraryIo. Closer io. Reader io. Readerat io. Seeker Stat () (OS. FileInfo, Error)}typeOsFsstruct{}//OsFs type, implements the FileSystem interface. func(OsFs) Open (namestring) (file, error)//As long as its return value, implement the file interface canfunc(OsFs) Stat (namestring) (OS. FileInfo, error)

Method expression (methods expressions)

typestruct{}  //定义了一个新的类型 Tfunc (T) Foo(string) {fmt.Println(s)}  //定义了这个类型T的一个方法//fn 是一个函数类型的变量,将这个方法赋值给这个变量// 值得注意的是: fn 的类型是 func(T, string)// Foo 函数的类型是: func (T) Foo(string) 类型varfunc(T, sring) = T.Foo  

A real example of the os/exec:

Func (c*cmd) stdin () (f*os. File, error) func (c*cmd) stdout () (f*os. File, error) func (c*cmd) stderr () (f*os. File, error) type F func (*cmd) (*os. File, error) for _, SETUPFD: = range []f{(*cmd). stdin, (*cmd). StdOut, (*cmd). stderr} {//Defines a slice of FD, err: = STEUPFD (c)ifErr! = Nil {c.closedescriptors (C.closeafterstart) c.closedescriptors (c.closeafterwait)returnERR} c.childfiles = append (C.childfiles, FD)}

Send and receive on the same channel

 PackageMainImport "FMT"varBattle = Make(Chan string)//define a channel variablefuncWarrior (namestring, doneChan struct{}) {//Now the question is: How should the same channel situation be addressed in the same select?     Select{ CaseOppoent: = <-battle://battle Accept DataFmt. Printf ("%s beat%s\n", name, oppoent) CaseBattle <-Name://battle sending Data        //I lost} Done <-struct{}{}}funcMain () {done: = Make(Chan struct{}) Langs: = []string{"Go","C","C + +","Java","Perl","Python"} for_, S: =Rangelangs {GoWarrior (S, done)//Generate multiple Goroutine} for_ =Rangelangs {<-done//wait for goroutine to end, when the whole process is over? }}

Run the program multiple times, the output is not the same:
Run for the first time:

Java beat C + +
Go beat C
Perl beat Python

Second run:

Python beat Perl
Go beat C
C + + beat Java

Now the question is:
1. In the same select, if there are two or more two case statements: what happens when the same channel is receiving data?
2. What happens when the same channel sends data at the same time?
3. What happens to the same channel (sending and receiving) data? Will there be spontaneous self-collection?

Own guesses:
1. If there are two channel transmit data at the same time, will randomly select a channel to send data
2. If there are two channel receivers receiving data at the same time, a channel is randomly selected to receive the data .
3. The same channel (transmit and receive) data does not generate spontaneous self-collection and will block in this channel.
For the above example, how does a specific select work and do not understand? (ask for high-finger teaching)

Using close to broadcast (broadcast with close)

 PackageMainImport("FMT"    "Math/rand"  //write like this    "Time")funcWaiter (iint, block, doneChan struct{}) {time. Sleep (time. Duration (Rand. Intn( in) * Time.millisecond) FMT. Println (I,"Waiting ...") <-block//All goroutine will block here until close (block)Fmt. Println (I,"done!") Done <-struct{}{}}funcMain () {block, Done: = Make(Chan struct{}), Make(Chan struct{}) forI: =0; I <4; i++ {GoWaiter (I, block, done)} time. Sleep(5* Time. Second)Close(block)//Shut down, all blocked blocks will stop blocking (equivalent to a broadcast)     forI: =0; I <4; The output of the i++ {<-done}} program is as follows:3Waiting ...2Waiting ...1Waiting ...0Waiting ...3done!2done!1done!0done!
    1. First, all the goroutine will be blocked in "<-block here."
    2. When the goroutine of Main is close (block), all blocks will not block again.
    3. Equivalent to a broadcast using close ()

NIl Channel in Select

funcWorker (IintChChanWork, quitChan struct{}) { for{Select{ CaseW: =<-Ch:ifQuit = =Nil{//a channel = = nil?W.refuse (); Fmt. Println ("Worker"I"refused", W) Break; } w.do (); Case<-quit:fmt. Println ("Worker"I"Quiting") quit =Nil(Assigned asNil) } }}funcMain () {ch, quit: = Make(ChanWork), Make(Chan struct{})GoMakework (CH) forI: =0; I <4; i++ {GoWorker (I, CH, quit)} time. Sleep(5* Time. Second)Close(quit) time. Sleep(2* Time. Second)}

Some of the above code doesn't know much about the place.
1. When a close (quit), then quit from a normal channel into nil? (should not)
2. If no quit is returned, the worker is always working.
3. When quit returns from the back, quit = nil, and then the worker will quit if he or she is ordered to do the work.


In general, the more difficult place is the channel and the struct.
1. Channel of various uses, to achieve synchronous and asynchronous, concurrency and other functions. It can only be explored in code.
2. About Golang memory model these things, not very understanding, many places shady. Can only wait to understand slowly later.

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.