Golang - How to add a method to struct type? Code Example

The code for How to add a method to struct type?

// Go language program to add a method to struct type

package main

import "fmt"

// Declaring a struct
type Rectange struct {
	length, width int
}

func (re Rectange) Area() int {
	return re.length * re.width
}

func main() {
	r := Rectange{5, 8}
	fmt.Println("Length and Width are:", r)
	fmt.Println("Area of Rectangle: ", r.Area())
}


/*
Output:
Length and Width are: {5 8}
Area of Rectangle:  40
*/
Code by IncludeHelp, on March 1, 2023 07:40

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.