Method in Golang

PROGRAM:

package main

import "fmt"

/* group the variable using struct */
type Rectangle struct {
length int
width int
}

/* Area function implemented for Rectangle type */
func (r Rectangle) Area() int {
return r.length * r.width
}

func (r Rectangle) Perimeter() int {
return 2 * (r.length * r.width)
}

func main() {
/* create a variable of type Rectangle and initialize it */
rect := Rectangle{15, 30}
/* call the method 'Area' using . operator */
area := rect.Area()
perimeter := rect.Perimeter()
fmt.Println("Length-", rect.length, " Width-", rect.width,
" Area-", area, " Perimeter-", perimeter)
}

OUTPUT:

Length- 15  Width- 30  Area- 450  Perimeter- 900

No comments:

Post a Comment