mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 15:24:09 +03:00
[go/en] Fix veriadic function bug; format and clarify comments.
This commit is contained in:
parent
88492baf33
commit
2655b4d056
146
go.html.markdown
146
go.html.markdown
@ -6,6 +6,7 @@ filename: learngo.go
|
||||
contributors:
|
||||
- ["Sonia Keys", "https://github.com/soniakeys"]
|
||||
- ["Christopher Bess", "https://github.com/cbess"]
|
||||
- ["Jesse Johnson", "https://github.com/holocronweaver"]
|
||||
---
|
||||
|
||||
Go was created out of the need to get work done. It's not the latest trend
|
||||
@ -30,9 +31,10 @@ package main
|
||||
|
||||
// Import declaration declares library packages referenced in this file.
|
||||
import (
|
||||
"fmt" // A package in the Go standard library
|
||||
"fmt" // A package in the Go standard library.
|
||||
"net/http" // Yes, a web server!
|
||||
"strconv" // String conversions
|
||||
"strconv" // String conversions.
|
||||
m "math" // Math library with local alias m.
|
||||
)
|
||||
|
||||
// A function definition. Main is special. It is the entry point for the
|
||||
@ -53,49 +55,49 @@ func beyondHello() {
|
||||
x = 3 // Variable assignment.
|
||||
// "Short" declarations use := to infer the type, declare, and assign.
|
||||
y := 4
|
||||
sum, prod := learnMultiple(x, y) // function returns two values
|
||||
fmt.Println("sum:", sum, "prod:", prod) // simple output
|
||||
sum, prod := learnMultiple(x, y) // Function returns two values.
|
||||
fmt.Println("sum:", sum, "prod:", prod) // Simple output.
|
||||
learnTypes() // < y minutes, learn more!
|
||||
}
|
||||
|
||||
// Functions can have parameters and (multiple!) return values.
|
||||
func learnMultiple(x, y int) (sum, prod int) {
|
||||
return x + y, x * y // return two values
|
||||
return x + y, x * y // Return two values.
|
||||
}
|
||||
|
||||
// Some built-in types and literals.
|
||||
func learnTypes() {
|
||||
// Short declaration usually gives you what you want.
|
||||
s := "Learn Go!" // string type
|
||||
s := "Learn Go!" // string type.
|
||||
|
||||
s2 := `A "raw" string literal
|
||||
can include line breaks.` // same string type
|
||||
can include line breaks.` // Same string type.
|
||||
|
||||
// non-ASCII literal. Go source is UTF-8.
|
||||
g := 'Σ' // rune type, an alias for uint32, holds a unicode code point
|
||||
// Non-ASCII literal. Go source is UTF-8.
|
||||
g := 'Σ' // rune type, an alias for uint32, holds a unicode code point.
|
||||
|
||||
f := 3.14195 // float64, an IEEE-754 64-bit floating point number
|
||||
c := 3 + 4i // complex128, represented internally with two float64s
|
||||
f := 3.14195 // float64, an IEEE-754 64-bit floating point number.
|
||||
c := 3 + 4i // complex128, represented internally with two float64's.
|
||||
|
||||
// Var syntax with an initializers.
|
||||
var u uint = 7 // unsigned, but implementation dependent size as with int
|
||||
var u uint = 7 // Unsigned, but implementation dependent size as with int.
|
||||
var pi float32 = 22. / 7
|
||||
|
||||
// Conversion syntax with a short declaration.
|
||||
n := byte('\n') // byte is an alias for uint8
|
||||
n := byte('\n') // byte is an alias for uint8.
|
||||
|
||||
// Arrays have size fixed at compile time.
|
||||
var a4 [4]int // an array of 4 ints, initialized to all 0
|
||||
a3 := [...]int{3, 1, 5} // an array of 3 ints, initialized as shown
|
||||
var a4 [4]int // An array of 4 ints, initialized to all 0.
|
||||
a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown.
|
||||
|
||||
// Slices have dynamic size. Arrays and slices each have advantages
|
||||
// but use cases for slices are much more common.
|
||||
s3 := []int{4, 5, 9} // compare to a3. no ellipsis here
|
||||
s4 := make([]int, 4) // allocates slice of 4 ints, initialized to all 0
|
||||
var d2 [][]float64 // declaration only, nothing allocated here
|
||||
bs := []byte("a slice") // type conversion syntax
|
||||
s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here.
|
||||
s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0.
|
||||
var d2 [][]float64 // Declaration only, nothing allocated here.
|
||||
bs := []byte("a slice") // Type conversion syntax.
|
||||
|
||||
p, q := learnMemory() // declares p, q to be type pointer to int.
|
||||
p, q := learnMemory() // Declares p, q to be type pointer to int.
|
||||
fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
|
||||
|
||||
// Maps are a dynamically growable associative array type, like the
|
||||
@ -109,23 +111,23 @@ can include line breaks.` // same string type
|
||||
// Output of course counts as using a variable.
|
||||
fmt.Println(s, c, a4, s3, d2, m)
|
||||
|
||||
learnFlowControl() // back in the flow
|
||||
learnFlowControl() // Back in the flow.
|
||||
}
|
||||
|
||||
// Go is fully garbage collected. It has pointers but no pointer arithmetic.
|
||||
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
|
||||
func learnMemory() (p, q *int) {
|
||||
// Named return values p and q have type pointer to int.
|
||||
p = new(int) // built-in function new allocates memory.
|
||||
p = new(int) // Built-in function new allocates memory.
|
||||
// The allocated int is initialized to 0, p is no longer nil.
|
||||
s := make([]int, 20) // allocate 20 ints as a single block of memory
|
||||
s[3] = 7 // assign one of them
|
||||
r := -2 // declare another local variable
|
||||
s := make([]int, 20) // Allocate 20 ints as a single block of memory.
|
||||
s[3] = 7 // Assign one of them.
|
||||
r := -2 // Declare another local variable.
|
||||
return &s[3], &r // & takes the address of an object.
|
||||
}
|
||||
|
||||
func expensiveComputation() int {
|
||||
return 1e6
|
||||
func expensiveComputation() float64 {
|
||||
return m.Exp(10)
|
||||
}
|
||||
|
||||
func learnFlowControl() {
|
||||
@ -135,29 +137,31 @@ func learnFlowControl() {
|
||||
}
|
||||
// Formatting is standardized by the command line command "go fmt."
|
||||
if false {
|
||||
// pout
|
||||
// Pout.
|
||||
} else {
|
||||
// gloat
|
||||
// Gloat.
|
||||
}
|
||||
// Use switch in preference to chained if statements.
|
||||
x := 1
|
||||
x := 42.0
|
||||
switch x {
|
||||
case 0:
|
||||
case 1:
|
||||
// cases don't "fall through"
|
||||
case 2:
|
||||
// unreached
|
||||
case 42:
|
||||
// Cases don't "fall through".
|
||||
case 43:
|
||||
// Unreached.
|
||||
}
|
||||
// Like if, for doesn't use parens either.
|
||||
for x := 0; x < 3; x++ { // ++ is a statement
|
||||
// Variables declared in for and if are local to their scope.
|
||||
for x := 0; x < 3; x++ { // ++ is a statement.
|
||||
fmt.Println("iteration", x)
|
||||
}
|
||||
// x == 1 here.
|
||||
// x == 42 here.
|
||||
|
||||
// For is the only loop statement in Go, but it has alternate forms.
|
||||
for { // infinite loop
|
||||
break // just kidding
|
||||
continue // unreached
|
||||
for { // Infinite loop.
|
||||
break // Just kidding.
|
||||
continue // Unreached.
|
||||
}
|
||||
// As with for, := in an if statement means to declare and assign y first,
|
||||
// then test y > x.
|
||||
@ -166,30 +170,17 @@ func learnFlowControl() {
|
||||
}
|
||||
// Function literals are closures.
|
||||
xBig := func() bool {
|
||||
return x > 100 // references x declared above switch statement.
|
||||
return x > 100 // References x declared above switch statement.
|
||||
}
|
||||
fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x)
|
||||
x /= 1e5 // this makes it == 10
|
||||
fmt.Println("xBig:", xBig()) // false now
|
||||
fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x).
|
||||
x /= m.Exp(9) // This makes x == e.
|
||||
fmt.Println("xBig:", xBig()) // false now.
|
||||
|
||||
// When you need it, you'll love it.
|
||||
goto love
|
||||
love:
|
||||
|
||||
// Good stuff coming up!
|
||||
learnVariadicParams("great", "learning", "here!")
|
||||
learnInterfaces()
|
||||
}
|
||||
|
||||
// Functions can have variadic parameters
|
||||
func learnVariadicParams(myStrings ...string) {
|
||||
// iterate each value of the variadic
|
||||
for _, param := range myStrings {
|
||||
fmt.Println("param:", param)
|
||||
}
|
||||
|
||||
// pass variadic value as a variadic parameter
|
||||
fmt.Println("params:", fmt.Sprintln(myStrings...))
|
||||
learnInterfaces() // Good stuff coming up!
|
||||
}
|
||||
|
||||
// Define Stringer as an interface type with one method, String.
|
||||
@ -213,16 +204,29 @@ func learnInterfaces() {
|
||||
// Brace syntax is a "struct literal." It evaluates to an initialized
|
||||
// struct. The := syntax declares and initializes p to this struct.
|
||||
p := pair{3, 4}
|
||||
fmt.Println(p.String()) // call String method of p, of type pair.
|
||||
var i Stringer // declare i of interface type Stringer.
|
||||
i = p // valid because pair implements Stringer
|
||||
fmt.Println(p.String()) // Call String method of p, of type pair.
|
||||
var i Stringer // Declare i of interface type Stringer.
|
||||
i = p // Valid because pair implements Stringer
|
||||
// Call String method of i, of type Stringer. Output same as above.
|
||||
fmt.Println(i.String())
|
||||
|
||||
// Functions in the fmt package call the String method to ask an object
|
||||
// for a printable representation of itself.
|
||||
fmt.Println(p) // output same as above. Println calls String method.
|
||||
fmt.Println(i) // output same as above
|
||||
fmt.Println(p) // Output same as above. Println calls String method.
|
||||
fmt.Println(i) // Output same as above.
|
||||
|
||||
learnVariadicParams("great", "learning", "here!")
|
||||
}
|
||||
|
||||
// Functions can have variadic parameters.
|
||||
func learnVariadicParams(myStrings ...interface{}) {
|
||||
// Iterate each value of the variadic.
|
||||
for _, param := range myStrings {
|
||||
fmt.Println("param:", param)
|
||||
}
|
||||
|
||||
// Pass variadic value as a variadic parameter.
|
||||
fmt.Println("params:", fmt.Sprintln(myStrings...))
|
||||
|
||||
learnErrorHandling()
|
||||
}
|
||||
@ -237,7 +241,7 @@ func learnErrorHandling() {
|
||||
}
|
||||
// An error value communicates not just "ok" but more about the problem.
|
||||
if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value
|
||||
// prints "strconv.ParseInt: parsing "non-int": invalid syntax"
|
||||
// prints 'strconv.ParseInt: parsing "non-int": invalid syntax'
|
||||
fmt.Println(err)
|
||||
}
|
||||
// We'll revisit interfaces a little later. Meanwhile,
|
||||
@ -264,19 +268,19 @@ func learnConcurrency() {
|
||||
// There is no telling in what order the results will arrive!
|
||||
fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator.
|
||||
|
||||
cs := make(chan string) // another channel, this one handles strings.
|
||||
cc := make(chan chan string) // a channel of string channels.
|
||||
go func() { c <- 84 }() // start a new goroutine just to send a value
|
||||
go func() { cs <- "wordy" }() // again, for cs this time
|
||||
cs := make(chan string) // Another channel, this one handles strings.
|
||||
ccs := make(chan chan string) // A channel of string channels.
|
||||
go func() { c <- 84 }() // Start a new goroutine just to send a value.
|
||||
go func() { cs <- "wordy" }() // Again, for cs this time.
|
||||
// Select has syntax like a switch statement but each case involves
|
||||
// a channel operation. It selects a case at random out of the cases
|
||||
// that are ready to communicate.
|
||||
select {
|
||||
case i := <-c: // the value received can be assigned to a variable
|
||||
case i := <-c: // The value received can be assigned to a variable,
|
||||
fmt.Printf("it's a %T", i)
|
||||
case <-cs: // or the value received can be discarded
|
||||
case <-cs: // or the value received can be discarded.
|
||||
fmt.Println("it's a string")
|
||||
case <-cc: // empty channel, not ready for communication.
|
||||
case <-ccs: // Empty channel, not ready for communication.
|
||||
fmt.Println("didn't happen.")
|
||||
}
|
||||
// At this point a value was taken from either c or cs. One of the two
|
||||
@ -287,7 +291,7 @@ func learnConcurrency() {
|
||||
|
||||
// A single function from package http starts a web server.
|
||||
func learnWebProgramming() {
|
||||
// ListenAndServe first parameter is TCP address to listen at.
|
||||
// First parameter of ListenAndServe is TCP address to listen to.
|
||||
// Second parameter is an interface, specifically http.Handler.
|
||||
err := http.ListenAndServe(":8080", pair{})
|
||||
fmt.Println(err) // don't ignore errors
|
||||
@ -295,7 +299,7 @@ func learnWebProgramming() {
|
||||
|
||||
// Make pair an http.Handler by implementing its only method, ServeHTTP.
|
||||
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Serve data with a method of http.ResponseWriter
|
||||
// Serve data with a method of http.ResponseWriter.
|
||||
w.Write([]byte("You learned Go in Y minutes!"))
|
||||
}
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user