首页 > 代码库 > Go语言练习之方法,接口,并发

Go语言练习之方法,接口,并发

多练练,有感觉了就写实际的东东。

package mainimport (	"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 float64func (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语言练习之方法,接口,并发