Code Monkey home page Code Monkey logo

gobyexample's People

Contributors

adam-singer avatar andrew-field avatar baileywickham avatar butuzov avatar c-ross avatar chrismckenzie avatar cn007b avatar deftly avatar eliben avatar everyx avatar gregimba avatar guettli avatar hyangah avatar jaywgraves avatar lcslitx avatar minikomi avatar mmcgrana avatar nikai3d avatar niyumard avatar nzoschke avatar oohira avatar owenthereal avatar peterbocan avatar peterzhu1992 avatar pzerone avatar simonjefford avatar skrul avatar techplexengineer avatar tleyden avatar zakj 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

gobyexample's Issues

gofmt uses spaces instead of tabs

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

worker pools example program can deadlock

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.

Update Pygmentize

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

./tools/build sed: can't read : No such file or directory

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?

Goroutines example needs a time.Sleep()

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

Comments with different languages

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/

missing "package" explainion

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.

Missing Networking section

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.

Confusing wording in Goroutines section

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."

Unable to run code in Go Playground

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.

generate hangs if pygmentize not in expected location

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
 }

Can't build as per README

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

Switching pages from every example page

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.

PDF export

It would be nice to have a PDF export in order to use it as offline reference on smartphones et al.

Could you add an example for recover()?

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

Could you add a Chinese version link

@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 :-)

Need suggestion about translation

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!

Closing-channel.go result ??

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 !

Consider more interactive code snippets via Sourcegraph?

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.

syntax highlighting is incorrect

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.

File read into a []byte slice issue...

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]))

[Problem] About Non-Blocking Channel Operations section

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.

enable running code elsewhere

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:

  • Providing a link to a playground version of the example
  • Providing a link to the complete commented source code (more direct than the current source link)
  • Enabling copy/paste of whole programs

Worker Pool example does not wait for jobs to finish

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.

Example of file path splitting?

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.

Comments

First page I tried to briefly look at1:

  • "Here we make a slice of ints of length 5 (initially empty-valued).": It's a zero value. There's no empty-value defined in the specs.
  • "We can set and get just like with arrays.": That's an index expression2.
  • "Note that we need to accept a return value from append as we may get a new slice reference.": 'append' always returns a "new" slice, they are values. The reference is one field of that value and that can be a newly allocated backing array. The term "new slice reference" is not mentioned nor defined by the specs.
  • "Slices support a “slice” operator, which is denoted with brackets containing :. ": There's no slice operator4. The index expression, again2, applies to slices, arrays and strings universally3.
  • "And this slices from the 4th index upwards.": s/4/5/.
  • "We can declare and initalize a slice in a single line as well.": Slices are not declared, but e.g. variables are. See also 5.

range: new example

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?

#126

Examples of commenting in Go

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.

How about mentioning waitGroup in the Worker Pool example?

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)

Examples of printing to various streams

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)

https://gobyexample.com/range-over-channels

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

line-filters splits lines

The line-filters example uses bufio.ReadLine, which may return an incomplete line:

  • I think it would be good to explain why a line might be incomplete.
  • line-filters outputs a newline when reading an incomplete line, thus splitting the line.

I think using ReadBytes or ReadString as recommended in the ReadLine documentation would be a better fit.

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.