Open supereagle opened 7 years ago
type User struct {
name string
address string
}
// Good practice with high efficiency
func getUsernames(users ...User) []string {
usernames := make([]string, len(users))
for _, user := range users {
usernames = append(usernames, user.name)
}
return usernames
}
// Bad practice with low efficiency
func getUsernames(users ...User) []string {
var usernames []string
for _, user := range users {
usernames = append(usernames, user.name)
}
return usernames
}
:=
is not allowed outside function bodypackage main
import "fmt"
name := "robin"
func main() {
fmt.Printf("Name is %s\n", name)
}
Compile Error:
.\main.go:5: syntax error: non-declaration statement outside function body
Solution:
The declaration name := "robin"
should be changed to var name string = "robin"
.
package main
import (
"fmt"
"time"
)
func main() {
// Need to declare for each element of the channel array.
var metrics [3]chan bool
for i := range metrics {
metrics[i] = make(chan bool)
}
go func() {
metrics[0] <- isHigh()
}()
go func() {
metrics[1] <- isSmart()
}()
go func() {
metrics[2] <- isRich()
}()
for _, metric := range metrics {
if result := <-metric; !result {
fmt.Println("Failure")
return
}
}
fmt.Println("Success")
}
func isHigh() bool {
fmt.Println("Measuring the high")
time.Sleep(1 * time.Second)
return false
}
func isSmart() bool {
fmt.Println("Measuring the IQ")
time.Sleep(5 * time.Second)
return true
}
func isRich() bool {
fmt.Println("Measuring the treasure")
time.Sleep(3 * time.Second)
return false
}
package main
import "fmt"
func main() {
const pi = 3.1415926
// Error: Cannot take the address of pi.
// address := &pi
// Correct: Use a temp variable to store the value of const, and then take its address.
tempVar := pi
address := &tempVar
fmt.Println(*address)
}
Category
EBooks
References