
- Go Tutorial
- Go - Home
- Go - Overview
- Go - Environment Setup
- Go - Program Structure
- Go - Basic Syntax
- Go - Data Types
- Go - Variables
- Go - Constants
- Go - Operators
- Go - Decision Making
- Go - Loops
- Go - Functions
- Go - Scope Rules
- Go - Strings
- Go - Arrays
- Go - Pointers
- Go - Structures
- Go - Slice
- Go - Range
- Go - Maps
- Go - Recursion
- Go - Type Casting
- Go - Interfaces
- Go - Error Handling
- Go Useful Resources
- Go - Questions and Answers
- Go - Quick Guide
- Go - Useful Resources
- Go - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Go - Method
Go programming language supports special types of functions called methods. In method declaration syntax, a "receiver" is present to represent the container of the function. This receiver can be used to call a function using "." operator. For example −
Syntax
func (variable_name variable_data_type) function_name() [return_type]{ /* function body*/ }
Example
package main import ( "fmt" "math" ) /* define a circle */ type Circle struct { x,y,radius float64 } /* define a method for circle */ func(circle Circle) area() float64 { return math.Pi * circle.radius * circle.radius } func main(){ circle := Circle{x:0, y:0, radius:5} fmt.Printf("Circle area: %f", circle.area()) }
When the above code is compiled and executed, it produces the following result −
Circle area: 78.539816
go_functions.htm
Advertisements