码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-04 11:07:12      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:veh   var   res   bounds   struct   pre   writer   math   type   

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

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

标签:veh   var   res   bounds   struct   pre   writer   math   type   

原文地址:http://www.cnblogs.com/aguncn/p/7115115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!