package main
import "fmt"
type s1 struct {
}
func (s *s1) prints1() {
fmt.Println("s1 print")
}
type s2 struct {
s1
}
func main() {
s := &s2{}
s.prints1()
}
package main
import (
"fmt"
)
func main() {
mymap := make(map[int]string)
mymap[1] = "test1"
mymap[2] = "test2"
mymap[3] = "test3"
mymap[4] = "test4"
fmt.Println(mymap)
for k, v := range mymap {
fmt.Println(k, v)
}
for k := range mymap {
if k == 1 {
delete(mymap, k) //如果C++这么写的话,迭代器会出问题。
}
}
fmt.Println(mymap)
}
输出:
map[4:test4 1:test1 2:test2 3:test3]
1 test1
2 test2
3 test3
4 test4
map[2:test2 3:test3 4:test4]
package main
import "fmt"
func testSlice() {
a := []int{1, 2, 3, 4, 5}
fmt.Println(a)
first := true
for i, userID := range a {
fmt.Println(i, userID)
if first {
a = a[:2]
}
fmt.Println(a)
}
}
func main() {
testSlice()
}
输出:
[1 2 3 4 5]
0 1
[1 2]
1 2
[1 2]
2 3
[1 2]
3 4
[1 2]
4 5
[1 2]
package main
import "fmt"
func testDump() {
a := []int{2, 2}
fmt.Println(a)
for i, userID := range a {
fmt.Println(i, userID)
if userID == 2 {
a = append(a[:i], a[i+1:]...)
}
fmt.Println(a)
}
}
func main() {
testDump()
}
输出:
$ go run test.go
[2 2]
0 2
[2]
1 2
panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.testDump()
e:/Go/GOPATH/src/jian/test/test.go:12 +0x3ef
main.main()
e:/Go/GOPATH/src/jian/test/test.go:33 +0x27
exit status 2
这种情况下会crash掉,所以在遍历的时候,最好还是不要乱修改。
package main
import "fmt"
func main() {
origin, wait := make(chan int), make(chan struct{})
Processor(origin, wait)
for num := 2; num < 1000; num++ {
origin <- num
}
close(origin)
<-wait
}
func Processor(seq chan int, wait chan struct{}) {
go func() {
prime, ok := <-seq
if !ok {
close(wait)
return
}
fmt.Println(prime)
out := make(chan int)
Processor(out, wait)
for num := range seq {
if num%prime != 0 {
out <- num
}
}
close(out)
}()
}
logfile, err := os.OpenFile("accserver.log", os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("%s\n", err.Error())
os.Exit(-1)
}
defer logfile.Close()
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds | log.Lshortfile)
log.SetOutput(logfile)
package main
import (
"fmt"
"log"
"os"
)
func main() {
logfile, err := os.OpenFile("test.log", os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("%s\n", err.Error())
os.Exit(-1)
}
defer logfile.Close()
arr := []int{2, 3}
logger := log.New(logfile, "", log.Ldate|log.Ltime|log.Lmicroseconds|log.Lshortfile)
logger.Print("arr", arr, "\n")
logger.Printf("arr[0] = %d", arr[0])
logger.Println("hello")
logger.Println("oh....")
logger.Fatal("test")
}
package main
import (
"flag"
"github.com/golang/glog"
)
func main() {
flag.Parse()
glog.Info("This is a Info log")
glog.Warning("This is a Warning log")
glog.Error("This is a Error log")
glog.Flush()
}
go run glog.go -log_dir=”./”
func WordCount(s string) map[string]int {
m := make(map[string]int)
words := strings.Fields(s)
for _, v := range words {
_, ok := m[v]
if ok {
m[v] = m[v] + 1
} else {
m[v] = 1
}
}
return m
}