Friday 3 May 2019

Go Language: Create a function


Functions are created using func keyword.

A simple function without parameters looks like below.

func functionName(){

}

Example
func sayHello(){
         fmt.Println("Hello!!!!!")
}

You can call the function using the staement ‘sayHello()’

HelloWorld.go
package main

import "fmt"

func main() {
 sayHello()
}

func sayHello(){
 fmt.Println("Hello!!!!!")
}

Output
Hello!!!!!

Parameterized functions
A function can take zero or more parameters.

Syntax
func functionName(parameter1 dataType, parameter2 dataType ….parameterN dataType){

}

Example
func sayHello(name string){
         fmt.Println("Hello!!!!! Mr.", name)
}

You can call sayHello function like below.

sayHello("Krishna")

name := "Ram"
sayHello(name)


HelloWorld.go
package main

import "fmt"

func main() {

 sayHello("Krishna")

 name := "Ram"
 sayHello(name)
 
}

func sayHello(name string){
 fmt.Println("Hello!!!!! Mr.", name)
}

Output
Hello!!!!! Mr. Krishna
Hello!!!!! Mr. Ram



Previous                                                 Next                                                 Home

No comments:

Post a Comment