Giter Club home page Giter Club logo

go101's Introduction

Go 101 is a series of books on Go programming. Currently, the following books are avaliable:

  • Go (Fundamentals) 101, which focuses on Go syntax/semantics (except custom generics related) and all kinds of runtime related things.
  • Go Generics 101, which explains Go custom generics in detail.
  • Go Optimizations 101, which provides some code performance optimization tricks, tips, and suggestions.
  • Go Details & Tips 101, which collects many details and provides several tips in Go programming.

These books are expected to help gophers gain a deep and thorough understanding of Go and be helpful for both beginner and experienced Go programmers.

To get latest news of Go 101 books, please follow the official twitter account @zigo_101.

Install, Update, and Read Locally

If you use Go toolchain v1.16+, then you don't need to clone the project respository:

### Install or update.

$ go install go101.org/go101@latest

### Read. (GOBIN path, defaulted as GOPATH/bin, should be set in PATH)

$ go101
Server started:
   http://localhost:55555 (non-cached version)
   http://127.0.0.1:55555 (cached version)

If you use Go toolchain v1.15-, or you would make some modifications (for contribution, etc.):

### Install.

$ git clone https://github.com/go101/go101.git

### Update. Enter the Go 101 project directory (which
# contains the current `README.md` file), then run

$ git pull

### Read. Enter the Go 101 project directory, then run

$ go run .
Server started:
   http://localhost:55555 (non-cached version)
   http://127.0.0.1:55555 (cached version)

The start page should be opened in a browser automatically. If it is not opened, please visit http://localhost:55555.

Options:

-port=1234
-theme=light # or dark (default is light)

Some HTML files are generated from their corresponding markdown files. If a markdown file is modified, we can run go run . -gen to synchronize its corresponding HTML file.

Contributing

Welcome to improve Go 101 by:

  • Submitting corrections for all kinds of mistakes, such as typos, grammar errors, wording inaccuracies, description flaws, code bugs and broken links.
  • Suggesting interesting Go related contents.

Current contributors are listed on this page.

Translations are also welcome. Here is a list of the ongoing translation projects:

License

Please read the LICENSE for more details.

go101's People

Contributors

1mark avatar 733amir avatar ahimani avatar arinto avatar bigwhite avatar caioleonhardt avatar cuonglm avatar dawkaka avatar deleplace avatar drejt avatar faridgh1991 avatar fatsheep9146 avatar golangsam avatar hhoke avatar ilwwli avatar ipinak avatar jasonhotsauce avatar joelrebel avatar juliawong avatar kirillovarchi avatar meefer avatar mneverov avatar pagliacii avatar russellluo avatar samirettali avatar samjberry avatar shalimski avatar siaw23-retired avatar xamenyap avatar zigo101 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go101's Issues

Channel Use Cases - slightly ungopheric code

In Channel Use Cases (at least) you seem to use a specific idiom, without much explanation:

func SomeFunction(inputs ...SomeTypeT) {
  for _, in := range inputs {
		in := in // this line is essential
		go func() {
			// ... some calculations using `in`
		}()
	}
}

A more conventional way of expressing this would be:

func SomeFunction(inputs ...SomeTypeT) {
  for _, in := range inputs {
		go func(in SomeTypeT) {
			// ... some calculations using `in`
		}(in)
	}
}

The outcome is the same, it just doesn't use obscure and misleading for newbies variable shadowing. I didn't look through the whole Go 101, but if you didn't explain why this construct is necessary, you definitely should. I've tripped over this a few times in the past.

Data Flow Manipulations suggestions

The section (Concurrent Programming > Channel Use Cases > Data Flow Manipulations) is pretty interesting actually and I liked it very much, after reading it I thought about some changes and I wanted to know your opinion about it:

in the section, you provided 7 modules that can be composed together to form data pipelines, looking at the examples I found that the modules Filter, Calculator, take the output channels as parameters.

I think it would be better to create the output channels from within the module functions because that way we can close the output channels in a cleaner way and at the right time.
so instead of this:

func Calculator(in <-chan uint64, out chan uint64) (<-chan uint64) {
	if out == nil {
		out = make(chan uint64)
	}
	go func() {
		for {
			x := <-in
			out <- ^x
		}
	}()
	return out
}

we can use this:

func Calculator(in <-chan uint64) (<-chan uint64) {
	out := make(chan uint64)
	go func() {
                for x := range in {
                     out <- ^x
                 }
                 close(out) 
	}()
	return out
}

I know you have stated that closing channels were not considered in the examples, but I think this issue affects our control over the channels and the way the functions are designed.
I also think using forrange in most of this section examples is better because I'm not sure how the provided code examples can break out from the for's.

I learned a lot from your book, and I am actually new to Go, so I'm sorry if I misunderstood anything, but I really want the best for this content. and I would really like to thank you for it.

Boolean case compile dependent

Hi :
When I'm using go version go1.11.2 to test The numeric constant case expressions in a switch block can't be deplicate, but boolean ones can example , found a compile error

switch false {
case false:	
case false:
}

It's looks like boolean case also make a compile dependent

Typo[s]

And channel may be not always the best solutuon for all use cases for data synchronizations.

solutuon

I'll collect typos here and submit them in a single commit.

Licensing policy

Hello!
First of all thank you for sharing this. This material of exceptional quality.

I'm also maintain my own (still publicity unavailable) short abstract (for personal needs only, not for sale) and want to borrow some quotes from your work (of course with references to original source).

Is it possible?

[basic-code-elements-introduction.html] A period is missing in line 258

A period is missing in line 258:
"There are some blank lines in the above program, to make the code get a better readability. And as this program is for code elements introduction purpose, there are many comments in it. Except the documentation comment for the StatRandomNumbers, other comments are for demostration purpose only We should try to make code self-explanatory and only use neccessary comments in formal projects."

Goexit with panic

In article https://go101.org/article/panic-and-recover-more.html

package main

import "runtime"

func f() {
	defer func() {
		recover()
	}()
	defer panic("will cancel Goexit but should not")
	runtime.Goexit()
}

func main() {
	c := make(chan struct{})
	go func() {
		defer close(c)
		f()
		for {
			runtime.Gosched()
		}
	}()
	<-c
}

The following is another example neither gc nor gccgo compiles it correctly. The example program should exit quickly in running, but in fact it never exit if it is compiled with the current versions of gc and gccgo.

This example will exit since go1.14 runtime.Goexit can no longer be aborted by a recursive panic/recover. https://golang.org/doc/go1.14#pkg-runtime

E-book

Is there any way we can read this lovely book on our e-readers? Thanks a ton?

Use time.Timer Values Incorrectly

https://go101.org/article/concurrent-common-mistakes.html

the Stop method of a *Timer value returns false if the corresponding Timer value has already expired or been stopped. If the Stop method returns false, and we know the Timer value has not been stopped yet, then the Timer value must have already expired.

I can't understand If the Stop method returns false, and we know the Timer value has not been stopped yet, then the Timer value must have already expired.

AFAIK, if the Timer value has not been stopped or has not expired, the Stop will return true.

Do I miss something here?

my code example

Comma (,) Will Not Be Inserted Automatically

page url : https://go101.org/article/line-break-rules.html

example:

func f1(a int, b string,) (x bool, y int,) {
	return true, 789
}
var f2 func (a int, b string) (x bool, y int)
var f3 func (a int, b string, // need the last comma
) (x bool, y int,             // need the last comma
)
var _ = []int{2, 3, 5, 7, 9,} // need the last comma     PS:no need
var _ = []int{2, 3, 5, 7, 9,  // need the last comma
}
var _ = []int{2, 3, 5, 7, 9}
var _, _ = f1(123, "Go",) // need the last comma        PS:no need
var _, _ = f1(123, "Go",  // need the last comma
)
var _, _ = f1(123, "Go")

A typo in the section - the go toolchain

"it is requred" should be "it is required

since Go Toolchain 1.11, if the environment variable GO111MODULE is set as on (we can use the
command go env to check all Go related environment variables), it is requred to create a go.mod
file containing a directive line like module my.module in the same folder containing the Go source
files. The go.mod file can be generated by running the command go mod init my.module .

perfect clone slice and its cap

package main

import "fmt"

func CloneSlice(a []int) []int {
	return append(a[:0:0], a...)
}

func main() {
	a := make([]int, 3, 5)
	b := CloneSlice(a)
	fmt.Printf("cap of a is %v\n", cap(a))
	fmt.Printf("cap of b is %v\n", cap(b))
}

the result:
cap of a is 5
cap of b is 4

Is there a way to perfectly clone slice and its cap? (in short form)

A known but not short way:

func CloneSlice(a []int) []int {
	if nil == a {
		return nil
	}
	b := make([]int, len(a), cap(a))
	copy(b, a)
	return b
}

Typos in Channel article

https://go101.org/article/channel.html

Channel Operations -> Point 4
Second word of citation should be "return".

The rerurn value is an int value.

Channel Operations -> Point 5
Function should be "len", as mentioned in the line after the code block.
Also again, the article is talking of "rerurn values" :)

cap(ch)
The rerurn value is an int value.

Thanks for the wonderful articles!

About "How to Gracefully Close Channels" confused.

I am sorry for my english is poor.
The problem is :
I add a line code to send 1 to chan ,and the function output is error:
as follow:

package main

import "fmt"

type T int

func IsClosed(ch <-chan T) bool {
	select {
	case <-ch:
		return true
	default:
	}

	return false
}

func main() {
	c := make(chan T,1)
	c <-1  // **i add code in here**
	fmt.Println(IsClosed(c)) // false
	close(c)
	fmt.Println(IsClosed(c)) // true
}

the ouput is :
true
true

context package in Concurrent Programming

This is the most complete book about golang i ever read, thanks for such a great book 👍

But i think in Concurrent Programing you should explain a little about context package too.

question: Why must the receiving goroutine be empty if there are values in the buffer?

sorry but don't know where else to ask.

I'm trying to understand this comment:

At any time, if the value buffer is not empty, then its receiving goroutine queue must be empty.

Why must the receiving goroutine be empty if there are values in the buffer?? Isn't the point of the receiving goroutine to receive values from the buffer?

similarly:

At any time, if the value buffer is not full, then its sending goroutine queue must be empty.

thanks in advanced.

context:

By the rules listed above, we can get some facts about the internal queues of a channel.
If the channel is closed, both of its sending goroutine queue and receiving goroutine queue must be empty, but its value buffer queue may not be empty.
At any time, if the value buffer is not empty, then its receiving goroutine queue must be empty.
At any time, if the value buffer is not full, then its sending goroutine queue must be empty.
If the channel is buffered, then at any time, one of its sending goroutine queue and receiving goroutine queue must be empty.
If the channel is unbufferd, then at any time, generally one of its sending goroutine queue and the receiving goroutine queue must be empty, but with an exception that a goroutine may be pushed into both of the two queues when executing a select control flow code block.

Go Generics

Ever since the release of the go2go tool which allows for the usage of generics in Golang, you haven't included it in your great and awesome book "Go101".
I think I speak for some when I say that you should add a few topics in your book that include Golang generics usage, installation.

Pointers operator precedence correction

Hi, I really enjoy your book, great work! I've found a small in the text, however. In the article on pointers it says:

If p is a pointer to a numeric value, compilers will view *p++ is a legal statement and treat it as (*p)++. In other words, the precedence of the address-taken operator & and the pointer dereference operator * is higher than the increment operator ++ and decrement operator --.

My concern is about & operator: It's actually illegal to write something like &i++ or &(i++). So it seems incorrect to say that the precedence of & operator is higher than --.

panic-and-recover

hi, go101 is very helpful for me. 👍

but when reading panic-and-recover of go101, i found someting wrong in the last example :

// This program exits without panic 1 being recovered.
package main

func demo() {
	defer func() {
		defer func() {
			recover() // this one recovers panic 2
		}()

		defer recover() // no-op

		panic(2)
	}()
	panic(1)
}

func main() {
	demo()
}

it says

In fact, the current Go specification also doesn't explain well why the second recover call, which is expected to recover panic 1, in the following example doesn't take effect.

and

What Go specification doesn't mention is that, at any given time, only the newest unrecovered panic in a goroutine is recoverable. In other words, each recover call is viewed as an attempt to recover the newest unrecovered panic in the currrent goroutine. This is why the second recover call in the above example is a no-op.

i do not think so.
the current verson of Go specification says :

The return value of recover is nil if any of the following conditions holds:

  1. panic's argument was nil;
  2. the goroutine is not panicking;
  3. recover was not called directly by a deferred function.

the third condition that is the reason why the second recover call, which is expected to recover panic 1, in the following example doesn't take effect.

then i found something interesting:

example 1 :

// This program exits without panic 1 being recovered.
package main

func demo() {
	defer func() {
		defer func() {
			recover() // this one recovers panic 2
		}()

		defer recover() // no-op

		panic(2)
	}()
	panic(1)
}

func main() {
	demo()
}

example 2 :

// This program exits with no panic.
package main

func demo() {
	defer func() {
		defer func() {
			recover() // this one recovers panic 2
		}()

		defer fmt.Println(recover()) // this one recover panic 1

		panic(2)
	}()
	panic(1)
}

func main() {
	demo()
}

example 3 :

// This program exits without panic 1 being recovered.
package main

func demo() {
	defer func() {
		defer func() {
			recover() // this one recovers panic 2
		}()

		defer func() {
			fmt.Println(recover()) //no-ops
		}()

		panic(2)
	}()
	panic(1)
}

func main() {
	demo()
}

now i know the reason why example 1 exit whit panic , but i don't know why example 2 and example 3 play different.

starting local server

go run main.go
.\main.go:29:8: undefined: openBrowser
.\main.go:34:5: undefined: go101

go run *.go
CreateFile *.go: The filename, directory name, or volume label syntax is incorrect.

go version go1.12.4 windows/amd64

what might be the problem?

In for-range aContainer may be not a anonymous copy

Hi, I'm studying go101 website, which gives me a lot of inspiration.

In https://go101.org/article/container.html, about for-range section
when aContainer is an arrary, modification about aContainer has effects on it.

package main

import "fmt"

func main() {
	type Person struct {
		name string
		age  int
	}
	persons := [2]Person {{"Alice", 28}, {"Bob", 25}}
	for i, p := range persons {
		fmt.Println(i, p)

		// Now this modification has effects
		// on the iteration.
		persons[1].name = "Jack"

		// This modification has not effects on
		// the persons array, for p is just a
		// copy of a copy of one persons element.
		p.age = 31
	}
	fmt.Println("persons:", &persons)
}

output is :

0 {Alice 28}
1 {Jack 25}
persons: &[{Alice 28} {Jack 25}]

and i tried to print the addresses of the origin persons out of for-range and the 'copyed' persons in for-range , they are the same!

by the way, i'm using the go1.14

May we translate your articles in go101.org?

Take the liberty to bother you.
We are volunteers of translation group from china and we are translating good technology articles from english to chinese. We found your articles in
go101.org are very good. We want to translate
you articles into chinese to make more chiese developpers and linuxers read
it conveniencly . We will keep author and website information
in translations. We will publish the articles in our website : linux.cn.
Can we get your license?

book: change `println` to `fmt.Println` entirely

Hey! Thanks for writing such an awesome book but I had noticed that you have used print and println for printing to stdout. These function use should be discouraged as its for bootstrapping and it can be removed whenever Go Team wants to.

I prefer we should switch to fmt.Println() and fmt.Print().

EDIT: I saw the opening pages which has a note about it but this should be scrapped and can be given in Some Special Topic.

The unsafe article states a runtime.KeepAlive call is needed in the String2ByteSlice example. This is wrong.

@bcmills's opinion is right in this thread.

func String2ByteSlice(str string) (bs []byte) {
	strHdr := (*reflect.StringHeader)(unsafe.Pointer(&str))
	sliceHdr := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
	sliceHdr.Data = strHdr.Data
	sliceHdr.Cap = strHdr.Len
	sliceHdr.Len = strHdr.Len
	// This KeepAlive line is essential to make the
	// String2ByteSlice function be always valid
	// when it is used in other custom packages.
	runtime.KeepAlive(&str)
	return
}

Bryan C. Mills said The GC tracks pointers through their original allocations — the pointer scan does not care about lexical types, only allocation types.

@tliron, as that old thread is frozen, so I created this thread to let you get acknowledged.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.