james-l
2/15/2017 - 6:40 PM

struct with method in go go语言中带有method的struct

struct with method in go go语言中带有method的struct

package main

import "fmt"

type person struct {
	firstname string
	lastname  string
	age       int
}

func (p person) fullname(sp string) string {
	return p.firstname + sp + p.lastname
}

func main() {
	p := person{"James", "Li", 40}
	fmt.Println(p.fullname(" "))
}
import (
    "fmt"
)

type rect struct {
    width int
    height int
}

// 可以使用指针
func (r *rect) area() int {
    return r.height * r.width
}

//或者是值类型
func (r rect) perim() int {
    return (r.width + r.width) * 2
}

func main() {
    r := rect{10,20}
    fmt.Println(r.area())
    fmt.Println(r.perim())

}