mmcgrana / gobyexample Goto Github PK
View Code? Open in Web Editor NEWGo by Example
Home Page: https://gobyexample.com
Go by Example
Home Page: https://gobyexample.com
Thank you for putting Go by Example online. It has helped me a lot on my journey to learn Golang.
The 3rd paragraph on Range Over Channels states
If we didn’t close it we’d block on a 3rd receive in the loop.
But if we take close(queue)
out of the example, an error is created on the 3rd iteration.
Here is the result:
one
two
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/tmp/sandbox354051104/main.go:22 +0x120
In the Goroutines section:
"Our two goroutines are running asynchronously in separate goroutines now, so execution falls through to here."
I found this wording confusing. I think you mean to say:
"Our two functions are running asynchronously in separate goroutines now, so execution falls through to here."
The line-filters example uses bufio.ReadLine, which may return an incomplete line:
I think using ReadBytes or ReadString as recommended in the ReadLine documentation would be a better fit.
First page I tried to briefly look at1:
This has been super useful while I have been learning go, but I find myself switching between them very often, I was wondering if you could add a menu to navigate to any example on every page. I dug around in the source, and it doesn't seem like it would be too hard, but when I try to run generate.go
I get some weird error I don't understand.
So folks don't have to manually build the site from source every time they make a change.
I added a new example to the range examples.
I noticed that when I ran the rebuild command it replaced <em>
with _
... is this correct?
also how do people feel about this example?
This is the result of gobyexample/example/closing-channels/closing-channels.go in your website !
$ go run closing-channels.go
sent job 1
received job 1
sent job 2
received job 2
sent job 3
received job 3
sent all jobs
received all jobs
I want to ask whether the result is always the same , or different at runtime !
https://gobyexample.com/worker-pools
https://gobyexample.com/channel-synchronization
In these two (and maybe some others, i didn't read trough all of them) examples, buffering in unneeded.
Please, provide your reasoning for those examples or change those channels to be unbuffered.
Please update Pygmentize to last version & add to README.md info about need to install Python.
i.e. in OS X you can do it with
brew install python
On https://gobyexample.com/collection-functions a function that returns a map like:
Thanks for your work so far! This has really helped me pick up the language at a rapid pace.
Just a small request: Would you think it'll be a nice feature to add the various ways of redirecting output to various output streams available? (e.g. fmt package, maybe others)
Hi guy.
This https://gobyexample.com/mutexes is not work on both go play and local. it talk process take long.
It'd be useful to have a different color for visited example links.
A critical part of go is networking. A section should included about server architecture and some example client code.
Hopefully it won't just be HTTP, but a run-through of package "net" would be nice.
@mmcgrana , i have translated it to Chinese, this is the site, it is supported by github page, so i have modified some generate code, but the site is the same.
I'll sync it anytime, and I want you can add a Chinese version link to you readme or footer of the website page.
Thanks and good job :-)
I tried building locally but get the following failure:
$ go get
$ tools/build-loop
tools/generate.go:6:5: cannot find package "github.com/russross/blackfriday" in any of:
/Users/clint/Developer/Cellar/go/1.2/libexec/src/pkg/github.com/russross/blackfriday (from $GOROOT)
/Users/clint/Projects/Go/src/github.com/russross/blackfriday (from $GOPATH)
In tools/generate.go
you reference github.com/russross/blackfriday
which is not installed with the initial go get
call. Manually installing that with $ go get github.com/russross/blackfriday
first let me build the site
The tools/gofmt script specifies to use spaces instead of tabs.
Is there a particular reason for this and/or can we change it to tabs
Here's an example I wrote up for recover(). It would be nice if you included this in your examples.
package main
import "fmt"
func gandalf( doTalkTo bool ){
defer catch()
if(doTalkTo){
// Panic stops execution of the current function and stops unwinding the stack, calling an deferred functions along the way.
panic("You shall not pass!")
}
}
// catch() must be called as a deferred
func catch(){
// recover() regains control over the program execution when panic() is called.
// recover() returns is the argument passed from panic()
if r := recover(); r != nil {
fmt.Println("Error:", r)
} else {
fmt.Println("No problems occurred")
}
}
func main() {
gandalf(true)
gandalf(false)
//unwinds to the top of the stack and ends the program
panic("Where am I going?");
}
// Output:
// Error: You shall not pass!
// No problems occurred
// panic: Where am I going?
// goroutine 1 [running]:
// main.main()
Demo: http://play.golang.org/p/xu9Jd1YI0T
More information here:
Effective Go - The Program Language
The generate
command fails when pygmentize is not found at "/usr/local/bin/pygmentize" because the error for cmd.Start()
is not checked.
--- a/tools/generate.go
+++ b/tools/generate.go
@@ -38,11 +38,12 @@ func pipe(bin string, arg []string, src string) []byte {
cmd := exec.Command(bin, arg...)
in, _ := cmd.StdinPipe()
out, _ := cmd.StdoutPipe()
- cmd.Start()
+ err := cmd.Start()
+ check(err)
in.Write([]byte(src))
in.Close()
bytes, _ := ioutil.ReadAll(out)
- err := cmd.Wait()
+ err = cmd.Wait()
check(err)
return bytes
}
I have tried generating the static gobyexample with this repo but I get this error
./tools/build
sed: can't read : No such file or directory
So I skipped the build script as it is only this
#!/bin/bash
set -e
tools/format
tools/measure
tools/generate
and I performed
./tools/measure && ./tools/generate
from repository's root and I received the generated files in public/
but without the .html
suffixes (and therefore browsers try to download those files instead of parsing and displaying them).
So I performed this small patch:
diff --git a/templates/example.tmpl b/templates/example.tmpl
index dabad82..584ffd7 100644
--- a/templates/example.tmpl
+++ b/templates/example.tmpl
@@ -37,7 +37,7 @@
{{end}}
{{if .NextExample}}
<p class="next">
- Next example: <a href="{{.NextExample.Id}}">{{.NextExample.Name}}</a>.
+ Next example: <a href="{{.NextExample.Id}}.html">{{.NextExample.Name}}</a>.
</p>
{{end}}
<p class="footer">
diff --git a/templates/index.tmpl b/templates/index.tmpl
index 9c5c02f..65e22ab 100644
--- a/templates/index.tmpl
+++ b/templates/index.tmpl
@@ -35,7 +35,7 @@
<ul>
{{range .}}
- <li><a href="{{.Id}}">{{.Name}}</a></li>
+ <li><a href="{{.Id}}.html">{{.Name}}</a></li>
{{end}}
</ul>
<p class="footer">
diff --git a/tools/generate.go b/tools/generate.go
index 30d7291..8726033 100644
--- a/tools/generate.go
+++ b/tools/generate.go
@@ -270,7 +270,7 @@ func renderExamples(examples []*Example) {
_, err := exampleTmpl.Parse(mustReadFile("templates/example.tmpl"))
check(err)
for _, example := range examples {
- exampleF, err := os.Create(siteDir + "/" + example.Id)
+ exampleF, err := os.Create(siteDir + "/" + example.Id + ".html")
check(err)
exampleTmpl.Execute(exampleF, example)
}
and now it works. Don't you guys have this problem? Am I doing something wrong?
Consider explaining this in the multiple-return-values page.
String literals are highlighted in green. Keywords and some pre-declared identifiers are reddish. The issue I have is with the "some". Highlighting should be consistent.
Here is the list of predeclared identifiers from the spec:
http://golang.org/ref/spec#Predeclared_identifiers
And keywords:
http://golang.org/ref/spec#Keywords
I suggest that either pre-declared identifiers should not be highlighted at all (as they may be shadowed by some other declaration), or that they should all be highlighted in a different color to keywords.
When there are more workers than jobs, the program exits before jobs finish executing.
For example, set job count to 1 and keep worker count to 3. The program exits before the job has a chance to finish executing.
Users would like to run the example code elsewhere, especially on the Go playground and their local machines. Consider supporting this by, perhaps with one of:
Thank you for your book! I've learnt a lot.But would you please help me to understand following problem?
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
Would you please explain why this excuted the default clause, why messages <- msg:
is failed? We already have msg.Thx.
Something I ran into while using the language. We could add a page that describes people how to comment in the language. Keeping this as a placeholder for myself to add a diff to.
Hey Mark, thanks for making this excellent resource. It's a great learning tool for new members of my team who are picking up Go for the first time.
Would you accept a pull request to make the snippets on Go by Example more interactive? For example, this snippet could function like this to help newbies easily jump-to-def and explore the code. Or alternatively, have a small link like you do to code on the Go playground for each snippet.
In full transparency, I'm one of the creators of Sourcegraph, so I'm a little biased, but I think visitors would find interactive snippets really cool and useful.
As far as I follow the Worker Pool example, the only reason it stops on time is because the final loop to print the results is careful to loop exactly 5 times. There is no way for the worker
routines to close the results
channel to mark that they are all done.
Perhaps it would be useful to mention the option of waitGroup
(https://golang.org/pkg/sync/#WaitGroup), which is nicely demonstrated in https://nathanleclaire.com/blog/2014/02/21/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing-part-two-fixing-my-ooops/
(EDIT: Point to an updated blog post with corrected examples)
Been re-enforcing my readings of go with these examples (excellent btw). But there are no concrete examples of what the package declaration does or how that affects things. It would be great to show how writing your own package works in conjunction with "package main".
Thanks again.
https://gobyexample.com/reading-files
"Read some bytes from the beginning of the file. Allow up to 5 to be read but also note how many actually were read."
b1 := make([]byte, 5)
n1, err := f.Read(b1)
check(err)
fmt.Printf("%d bytes: %s\n", n1, string(b1))
Thing is, if less than 5 bytes are read, the remainder of the []byte slice will still contain NULL (\0) characters, and these will become part of string(b1) and be printed (perhaps invisibly, but still).
On the other hand, say the file is 6 bytes long. If the slice is reused later to read more bytes, the 2nd read will change the first byte only, and the rest of the slice will retain its contents from the first read.
If one wants to print this correctly, one should do this I guess:
fmt.Printf("%d bytes: %s\n", n1, string(b1[0:n1]))
Hello,
I would like to translate GoByExample into Russian. As I could see, a guy translated it into Chinese after building the HTML files.
So, what is actually a good way to translate this into another language?
Thanks!
A wrong variable in Filter(). Fix:
- for _, v := range elems {
+ for _, v := range vs {
See line 38
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
the Fprintln
statement should be:
fmt.Fprintln(os.Stderr, "error: %s", err)
The blank identifier is explained in the range section.
Yet it is used in the previous Maps section without explanation. The blank identifier should be explained in the Maps section.
I'm happy to put together a PR for this.
What about ability to add comments in different languages?
for example:
// en: This is english comment
// ru: This is Russian comment
// ch: This is China comment
And at compile time specify the flag for a compiled language.
This will give the opportunity for changed and new examples to quickly add and edit comments for different languages.
For now I fork your repo to translate for Russian language. And if happened changes in your repo I need to watch it & modify my files.
What do you think about it?
Pavel - author of Russian version of your perfect project http://gobyexample.ru/
Hello. I am working on a triditional chinese version of Go by Example for Hong Kong people and Taiwanese. Here is the link to the GitBook: https://www.gitbook.com/book/casperli/go-by-example/details
From a Google search I landed on https://gobyexample.com/stateful-goroutines which says
In the previous example we used […]
But I can't find any way to go to that previous example.
The generator should also include a «Previous example: Foo» link the same way it has a «Next example: Sorting» link.
Would you be interested in adding an example of file path splitting, accessing the file extension, and such? If yes, i can submit a PR with it.
The example relies on the fact that jobs
and results
channel buffers are big enough. If the code is changed to use smaller buffers for these channels:
jobs := make(chan int, 2)
results := make(chan int, 2)
then example program will deadlock: http://play.golang.org/p/whGg0n8qgT
Also in practice number of jobs is variable and it is hard to find the right size for the channels buffer that will work in all cases. This should at least be explained on the example page.
Hi,
I really enjoy learning Go with your examples but when I click the top right corner of the code block to redirect to Go Playground to run the code it shows
<h1>Unavailable For Legal Reasons</h1><p>If you believe this is in error, please <a href="https://golang.org/issue">file an issue</a>.</p>
This happens everytime I try to run the code (for example). I also tried to do the same thing with some examples in the Russian version and I got same messages.
I'm not sure whether you can reproduce the same issue but I can open play.golang.org and run code in there.
It would be nice to have a PDF export in order to use it as offline reference on smartphones et al.
Without time.Sleep(), the execution of goroutines isn't interleaved. It might also be worth noting in this early example why a Scanln is required—main() won't wait for goroutines to finish and since they're returned immediately getting to the end of main() ends the execution.
➜ goroutines git:(master) go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine : 1
goroutine : 2
going
done
Sorry, Nothing...
Please add Keyboard navigations for navigating lessons for eg: for next lesson
Hi mmcgrana.
I've translate this gobyexample
into korean one. So, could you add a link for korean version to your README?
Here is a link of korean version. https://mingrammer.com/gobyexample/
Thank you.
need examples with "testing" package
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.