基础语法

Hello World

  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println("Hello world")
  5. }
  1. print "Hello world"

Print

  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println("Some string")
  5. fmt.Print("Some string")
  6. fmt.Printf("Name: %s, Age: %d\n", "Peter", 35)
  7. }
  1. print "Some string"
  2. print("Some string") # Python 3
  3. print "Some string", # no newline character printed
  4. print "Name: %s, Age: %d" % ('Peter', 35)

Comments

  1. package main
  2. // This is a general comment
  3. /* This is also a comment
  4. but on multiple lines.
  5. */
  6. /* This is the multi-line comment for the function main().
  7. To get access to this from the command line, run:
  8. godoc comments.go
  9. */
  10. func main() {
  11. }
  1. """This is a doc string for the whole module"""
  2. # This is a inline comment
  3. class Class(object):
  4. """This is the doc string for the class"""
  5. print __doc__
  6. print Class.__doc__

Boolean

  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println(true && false) // false
  5. fmt.Println(true || false) // true
  6. fmt.Println(!true) // false
  7. x := 1
  8. if x != 0 {
  9. fmt.Println("Yes")
  10. }
  11. var y []string
  12. if len(y) != 0 {
  13. fmt.Println("this won't be printed")
  14. }
  15. }
  1. print True and False # False
  2. print True or False # True
  3. print not True # False

控制结构

Loop

  1. package main
  2. import "fmt"
  3. func main() {
  4. i := 1
  5. for i <= 10 {
  6. fmt.Println(i)
  7. i += 1
  8. }
  9. // same thing more but more convenient
  10. for i := 1; i <= 10; i++ {
  11. fmt.Println(i)
  12. }
  13. }
  1. i = 1
  2. while i <= 10:
  3. print i
  4. i += 1
  5. # ...or...
  6. for i in range(1, 11):
  7. print i

Range

  1. package main
  2. import "fmt"
  3. func main() {
  4. names := []string{
  5. "Peter",
  6. "Anders",
  7. "Bengt",
  8. }
  9. /* This will print
  10. 1. Peter
  11. 2. Anders
  12. 3. Bengt
  13. */
  14. for i, name := range names {
  15. fmt.Printf("%d. %s\n", i+1, name)
  16. }
  17. }
  1. names = ["Peter", "Anders", "Bengt"]
  2. for i, name in enumerate(names):
  3. print "%d. %s" % (i + 1, name)

Switch

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func str2int(s string) int {
  7. i, err := strconv.Atoi(s)
  8. if err != nil {
  9. panic("Not a number")
  10. }
  11. return i
  12. }
  13. func main() {
  14. var number_string string
  15. fmt.Scanln(&number_string)
  16. number := str2int(number_string)
  17. switch number {
  18. case 8:
  19. fmt.Println("Oxygen")
  20. case 1:
  21. fmt.Println("Hydrogen")
  22. case 2:
  23. fmt.Println("Helium")
  24. case 11:
  25. fmt.Println("Sodium")
  26. default:
  27. fmt.Printf("I have no idea what %d is\n", number)
  28. }
  29. // Alternative solution
  30. fmt.Scanln(&number_string)
  31. db := map[int]string{
  32. 1: "Hydrogen",
  33. 2: "Helium",
  34. 8: "Oxygen",
  35. 11: "Sodium",
  36. }
  37. number = str2int(number_string)
  38. if name, exists := db[number]; exists {
  39. fmt.Println(name)
  40. } else {
  41. fmt.Printf("I have no idea what %d is\n", number)
  42. }
  43. }
  1. def input():
  2. return int(raw_input())
  3. number = input()
  4. if number == 8:
  5. print "Oxygen"
  6. elif number == 1:
  7. print "Hydrogen"
  8. elif number == 2:
  9. print "Helium"
  10. elif number == 11:
  11. print "Sodium"
  12. else:
  13. print "I have no idea what %d is" % number
  14. # Alternative solution
  15. number = input()
  16. db = {
  17. 1: "Hydrogen",
  18. 2: "Helium",
  19. 8: "Oxygen",
  20. 11: "Sodium",
  21. }
  22. print db.get(number, "I have no idea what %d is" % number)

函数

可变参函数

  1. package main
  2. import "fmt"
  3. func average(numbers ...float64) float64 {
  4. total := 0.0
  5. for _, number := range numbers {
  6. total += number
  7. }
  8. return total / float64(len(numbers))
  9. }
  10. func main() {
  11. fmt.Println(average(1, 2, 3, 4)) // 2.5
  12. }
  1. from __future__ import division
  2. def average(*numbers):
  3. return sum(numbers) / len(numbers)
  4. print average(1, 2, 3, 4) # 10/4 = 2.5

闭包

  1. package main
  2. import "fmt"
  3. func main() {
  4. number := 0
  5. /* It has to be a local variable like this.
  6. You can't do `func increment(amount int) {` */
  7. increment := func(amount int) {
  8. number += amount
  9. }
  10. increment(1)
  11. increment(2)
  12. fmt.Println(number) // 3
  13. }
  1. def run():
  2. def increment(amount):
  3. return number + amount
  4. number = 0
  5. number = increment(1)
  6. number = increment(2)
  7. print number # 3
  8. run()

常用数据结构

Slice/List

  1. package main
  2. import "fmt"
  3. func main() {
  4. // initialized array
  5. var numbers [5]int // becomes [0, 0, 0, 0, 0]
  6. // change one of them
  7. numbers[2] = 100
  8. // create a new slice from an array
  9. some_numbers := numbers[1:3]
  10. fmt.Println(some_numbers) // [0, 100]
  11. // length of it
  12. fmt.Println(len(numbers))
  13. // initialize a slice
  14. var scores []float64
  15. scores = append(scores, 1.1) // recreate to append
  16. scores[0] = 2.2 // change your mind
  17. fmt.Println(scores) // prints [2.2]
  18. // when you don't know for sure how much you're going
  19. // to put in it, one way is to
  20. var things [100]string
  21. things[0] = "Peter"
  22. things[1] = "Anders"
  23. fmt.Println(len(things)) // 100
  24. }
  1. # initialize list
  2. numbers = [0] * 5
  3. # change one of them
  4. numbers[2] = 100
  5. some_numbers = numbers[1:3]
  6. print some_numbers # [0, 100]
  7. # length of it
  8. print len(numbers) # 5
  9. # initialize another
  10. scores = []
  11. scores.append(1.1)
  12. scores[0] = 2.2
  13. print scores # [2.2]

Map

  1. package main
  2. import "fmt"
  3. func main() {
  4. elements := make(map[string]int)
  5. elements["H"] = 1
  6. fmt.Println(elements["H"])
  7. // remove by key
  8. elements["O"] = 8
  9. delete(elements, "O")
  10. // only do something with a element if it's in the map
  11. if number, ok := elements["O"]; ok {
  12. fmt.Println(number) // won't be printed
  13. }
  14. if number, ok := elements["H"]; ok {
  15. fmt.Println(number) // 1
  16. }
  17. }
  1. elements = {}
  2. elements["H"] = 1
  3. print elements["H"] # 1
  4. # remove by key
  5. elements["O"] = 8
  6. elements.pop("O")
  7. # do something depending on the being there
  8. if "O" in elements:
  9. print elements["O"]
  10. if "H" in elements:
  11. print elements["H"]

面向对象

Struct/Class

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. type Point struct {
  7. x float64
  8. y float64
  9. }
  10. func distance(point1 Point, point2 Point) float64 {
  11. return math.Sqrt(point1.x*point2.x + point1.y*point2.y)
  12. }
  13. // Since structs get automatically copied,
  14. // it's better to pass it as pointer.
  15. func distance_better(point1 *Point, point2 *Point) float64 {
  16. return math.Sqrt(point1.x*point2.x + point1.y*point2.y)
  17. }
  18. func main() {
  19. p1 := Point{1, 3}
  20. p2 := Point{2, 4}
  21. fmt.Println(distance(p1, p2)) // 3.7416573867739413
  22. fmt.Println(distance_better(&p1, &p2)) // 3.7416573867739413
  23. }
  1. from __future__ import division
  2. from math import sqrt
  3. class Point(object):
  4. def __init__(self, x, y):
  5. self.x = x
  6. self.y = y
  7. def distance(point1, point2):
  8. return sqrt(point1.x * point2.x + point1.y * point2.y)
  9. p1 = Point(1, 3)
  10. p2 = Point(2, 4)
  11. print distance(p1, p2) # 3.74165738677

方法

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. type Point struct {
  7. x float64
  8. y float64
  9. }
  10. func (this Point) distance(other Point) float64 {
  11. return math.Sqrt(this.x*other.x + this.y*other.y)
  12. }
  13. // Since structs get automatically copied,
  14. // it's better to pass it as pointer.
  15. func (this *Point) distance_better(other *Point) float64 {
  16. return math.Sqrt(this.x*other.x + this.y*other.y)
  17. }
  18. func main() {
  19. p1 := Point{1, 3}
  20. p2 := Point{2, 4}
  21. fmt.Println(p1.distance(p2)) // 3.7416573867739413
  22. fmt.Println(p1.distance_better(&p2)) // 3.7416573867739413
  23. }
  1. from __future__ import division
  2. from math import sqrt
  3. class Point(object):
  4. def __init__(self, x, y):
  5. self.x = x
  6. self.y = y
  7. def distance(self, other):
  8. return sqrt(self.x * other.x + self.y * other.y)
  9. p1 = Point(1, 3)
  10. p2 = Point(2, 4)
  11. print p1.distance(p2) # 3.74165738677
  12. print p2.distance(p1) # 3.74165738677

杂项

Goroutine

  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. )
  7. func f(url string) {
  8. response, err := http.Get(url)
  9. if err != nil {
  10. panic(err)
  11. }
  12. defer response.Body.Close()
  13. body, err := ioutil.ReadAll(response.Body)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Println(len(body))
  18. }
  19. func main() {
  20. urls := []string{
  21. "http://www.peterbe.com",
  22. "http://peterbe.com",
  23. "http://htmltree.peterbe.com",
  24. "http://tflcameras.peterbe.com",
  25. }
  26. for _, url := range urls {
  27. go f(url)
  28. }
  29. // necessary so it doesn't close before
  30. // the goroutines have finished
  31. var input string
  32. fmt.Scanln(&input)
  33. }
import urllib2
import multiprocessing

def f(url):
    req = urllib2.urlopen(url)
    try:
        print len(req.read())
    finally:
        req.close()


urls = (
    "http://www.peterbe.com",
    "http://peterbe.com",
    "http://htmltree.peterbe.com",
    "http://tflcameras.peterbe.com",
)

if __name__ == '__main__':
    p = multiprocessing.Pool(3)
    p.map(f, urls)

运行时参数

package main

import (
    "fmt"
    "os"
    "strings"
)

func transform(args []string) {
    for _, arg := range args {
        fmt.Println(strings.ToUpper(arg))
    }

}
func main() {
    args := os.Args[1:]
    transform(args)
}
import sys


def transform(*args):
    for arg in args:
        print arg.upper()

if __name__ == '__main__':
    transform(*sys.argv[1:])

import 别名

package main

import (
    "fmt"
    s "strings"
)

func main() {
    fmt.Println(s.ToUpper("world"))
}
import string as s

print s.upper("world")