基础语法
Hello World
package main
import "fmt"
func main() {
fmt.Println("Hello world")
}
print "Hello world"
Print
package main
import "fmt"
func main() {
fmt.Println("Some string")
fmt.Print("Some string")
fmt.Printf("Name: %s, Age: %d\n", "Peter", 35)
}
print "Some string"
print("Some string") # Python 3
print "Some string", # no newline character printed
print "Name: %s, Age: %d" % ('Peter', 35)
Comments
package main
// This is a general comment
/* This is also a comment
but on multiple lines.
*/
/* This is the multi-line comment for the function main().
To get access to this from the command line, run:
godoc comments.go
*/
func main() {
}
"""This is a doc string for the whole module"""
# This is a inline comment
class Class(object):
"""This is the doc string for the class"""
print __doc__
print Class.__doc__
Boolean
package main
import "fmt"
func main() {
fmt.Println(true && false) // false
fmt.Println(true || false) // true
fmt.Println(!true) // false
x := 1
if x != 0 {
fmt.Println("Yes")
}
var y []string
if len(y) != 0 {
fmt.Println("this won't be printed")
}
}
print True and False # False
print True or False # True
print not True # False
控制结构
Loop
package main
import "fmt"
func main() {
i := 1
for i <= 10 {
fmt.Println(i)
i += 1
}
// same thing more but more convenient
for i := 1; i <= 10; i++ {
fmt.Println(i)
}
}
i = 1
while i <= 10:
print i
i += 1
# ...or...
for i in range(1, 11):
print i
Range
package main
import "fmt"
func main() {
names := []string{
"Peter",
"Anders",
"Bengt",
}
/* This will print
1. Peter
2. Anders
3. Bengt
*/
for i, name := range names {
fmt.Printf("%d. %s\n", i+1, name)
}
}
names = ["Peter", "Anders", "Bengt"]
for i, name in enumerate(names):
print "%d. %s" % (i + 1, name)
Switch
package main
import (
"fmt"
"strconv"
)
func str2int(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic("Not a number")
}
return i
}
func main() {
var number_string string
fmt.Scanln(&number_string)
number := str2int(number_string)
switch number {
case 8:
fmt.Println("Oxygen")
case 1:
fmt.Println("Hydrogen")
case 2:
fmt.Println("Helium")
case 11:
fmt.Println("Sodium")
default:
fmt.Printf("I have no idea what %d is\n", number)
}
// Alternative solution
fmt.Scanln(&number_string)
db := map[int]string{
1: "Hydrogen",
2: "Helium",
8: "Oxygen",
11: "Sodium",
}
number = str2int(number_string)
if name, exists := db[number]; exists {
fmt.Println(name)
} else {
fmt.Printf("I have no idea what %d is\n", number)
}
}
def input():
return int(raw_input())
number = input()
if number == 8:
print "Oxygen"
elif number == 1:
print "Hydrogen"
elif number == 2:
print "Helium"
elif number == 11:
print "Sodium"
else:
print "I have no idea what %d is" % number
# Alternative solution
number = input()
db = {
1: "Hydrogen",
2: "Helium",
8: "Oxygen",
11: "Sodium",
}
print db.get(number, "I have no idea what %d is" % number)
函数
可变参函数
package main
import "fmt"
func average(numbers ...float64) float64 {
total := 0.0
for _, number := range numbers {
total += number
}
return total / float64(len(numbers))
}
func main() {
fmt.Println(average(1, 2, 3, 4)) // 2.5
}
from __future__ import division
def average(*numbers):
return sum(numbers) / len(numbers)
print average(1, 2, 3, 4) # 10/4 = 2.5
闭包
package main
import "fmt"
func main() {
number := 0
/* It has to be a local variable like this.
You can't do `func increment(amount int) {` */
increment := func(amount int) {
number += amount
}
increment(1)
increment(2)
fmt.Println(number) // 3
}
def run():
def increment(amount):
return number + amount
number = 0
number = increment(1)
number = increment(2)
print number # 3
run()
常用数据结构
Slice/List
package main
import "fmt"
func main() {
// initialized array
var numbers [5]int // becomes [0, 0, 0, 0, 0]
// change one of them
numbers[2] = 100
// create a new slice from an array
some_numbers := numbers[1:3]
fmt.Println(some_numbers) // [0, 100]
// length of it
fmt.Println(len(numbers))
// initialize a slice
var scores []float64
scores = append(scores, 1.1) // recreate to append
scores[0] = 2.2 // change your mind
fmt.Println(scores) // prints [2.2]
// when you don't know for sure how much you're going
// to put in it, one way is to
var things [100]string
things[0] = "Peter"
things[1] = "Anders"
fmt.Println(len(things)) // 100
}
# initialize list
numbers = [0] * 5
# change one of them
numbers[2] = 100
some_numbers = numbers[1:3]
print some_numbers # [0, 100]
# length of it
print len(numbers) # 5
# initialize another
scores = []
scores.append(1.1)
scores[0] = 2.2
print scores # [2.2]
Map
package main
import "fmt"
func main() {
elements := make(map[string]int)
elements["H"] = 1
fmt.Println(elements["H"])
// remove by key
elements["O"] = 8
delete(elements, "O")
// only do something with a element if it's in the map
if number, ok := elements["O"]; ok {
fmt.Println(number) // won't be printed
}
if number, ok := elements["H"]; ok {
fmt.Println(number) // 1
}
}
elements = {}
elements["H"] = 1
print elements["H"] # 1
# remove by key
elements["O"] = 8
elements.pop("O")
# do something depending on the being there
if "O" in elements:
print elements["O"]
if "H" in elements:
print elements["H"]
面向对象
Struct/Class
package main
import (
"fmt"
"math"
)
type Point struct {
x float64
y float64
}
func distance(point1 Point, point2 Point) float64 {
return math.Sqrt(point1.x*point2.x + point1.y*point2.y)
}
// Since structs get automatically copied,
// it's better to pass it as pointer.
func distance_better(point1 *Point, point2 *Point) float64 {
return math.Sqrt(point1.x*point2.x + point1.y*point2.y)
}
func main() {
p1 := Point{1, 3}
p2 := Point{2, 4}
fmt.Println(distance(p1, p2)) // 3.7416573867739413
fmt.Println(distance_better(&p1, &p2)) // 3.7416573867739413
}
from __future__ import division
from math import sqrt
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(point1, point2):
return sqrt(point1.x * point2.x + point1.y * point2.y)
p1 = Point(1, 3)
p2 = Point(2, 4)
print distance(p1, p2) # 3.74165738677
方法
package main
import (
"fmt"
"math"
)
type Point struct {
x float64
y float64
}
func (this Point) distance(other Point) float64 {
return math.Sqrt(this.x*other.x + this.y*other.y)
}
// Since structs get automatically copied,
// it's better to pass it as pointer.
func (this *Point) distance_better(other *Point) float64 {
return math.Sqrt(this.x*other.x + this.y*other.y)
}
func main() {
p1 := Point{1, 3}
p2 := Point{2, 4}
fmt.Println(p1.distance(p2)) // 3.7416573867739413
fmt.Println(p1.distance_better(&p2)) // 3.7416573867739413
}
from __future__ import division
from math import sqrt
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
return sqrt(self.x * other.x + self.y * other.y)
p1 = Point(1, 3)
p2 = Point(2, 4)
print p1.distance(p2) # 3.74165738677
print p2.distance(p1) # 3.74165738677
杂项
Goroutine
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func f(url string) {
response, err := http.Get(url)
if err != nil {
panic(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(len(body))
}
func main() {
urls := []string{
"http://www.peterbe.com",
"http://peterbe.com",
"http://htmltree.peterbe.com",
"http://tflcameras.peterbe.com",
}
for _, url := range urls {
go f(url)
}
// necessary so it doesn't close before
// the goroutines have finished
var input string
fmt.Scanln(&input)
}
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")