Go语言练习之方法,接口,并发
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go语言练习之方法,接口,并发相关的知识,希望对你有一定的参考价值。
多练练,有感觉了就写实际的东东。
package main import ( "fmt" "math" "os" "time" "net/http" "image" "runtime" ) func say(s string) { for i := 0; i < 5; i++ { runtime.Gosched() fmt.Println(s) } } type Hello struct{} func (h Hello) ServeHTTP( w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello") } type Abser interface { Abs() float64 } type Reader interface { Read(b []byte) (n int, err error) } type Writer interface { Write(b []byte) (n int, err error) } type ReadWriter interface { Reader Writer } type MyError struct { When time.Time What string } func (e *MyError) Error() string { return fmt.Sprintf("at %v, %s", e.When, e.What) } func run() error { return &MyError{ time.Now(), "it didn‘t work", } } type Vertex struct { X, Y float64 } func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func (v *Vertex) Scale(f float64) { v.X = v.X * f v.Y = v.Y *f } type MyFloat float64 func (f MyFloat) Abs() float64 { if f < 0 { return float64(-f) } return float64(f) } func main() { var a Abser var w Writer v := Vertex{3, 4} f := MyFloat(-math.Sqrt2) v.Scale(5) a = f fmt.Println(a.Abs()) a = &v fmt.Println(a.Abs()) w = os.Stdout fmt.Fprintf(w, "hello, writer\\n") if err := run(); err != nil { fmt.Println(err) } m := image.NewRGBA(image.Rect(0, 0, 100, 100)) fmt.Println(m.Bounds()) fmt.Println(m.At(0, 0).RGBA()) go say("world") say("hello") var h Hello http.ListenAndServe("localhost:4446", h) }
以上是关于Go语言练习之方法,接口,并发的主要内容,如果未能解决你的问题,请参考以下文章