Golang by Example

Logo

Functions

Functions are declared using the func keyword, followed by the function name, parameters, and return type. The syntax is as follows:

func functionName(parameter1 type1, parameter2 type2) returnType {
    // Function body
}

Function can take none, single, or multiple parameters. The returns can also be none, single, or multiple. For multiple returns, you can use parentheses to group the return types. In the function body, you can use the return statement to return values. If you don't need to return a value, you can omit that.

Activity

Now, since you have learned about structs and functions, create a struct named Rectangle with two fields Width and Height. Then create a function named CalculatePerimeter that calculates the area of the rectangle. The area of a rectangle is calculated by multiplying its width and height.


  type Rectangle struct {
      Width  float64
      Height float64
  }


  func CalculatePerimeter(r Rectangle) float64 {
      // Implement the function here
  }


💡 Quiz
Your task is to implement function called `CalculatePerimeter` that takes a `Rectangle` as an input argument and returns the perimeter of the rectangle.

Second Activity

Go to Hackerrank and solve the FizzBuzz problem. FizzBuzz problem is a classic programming challenge that requires you to print the numbers from 1 to 100. However, for multiples of three, print "Fizz" instead of the number, and for the multiples of five, print "Buzz". For numbers that are multiples of both three and five, print "FizzBuzz".

💡 Quiz
Do you finish the FizzBuzz problem already?

Table of contents

Hello World - Begin with the classic Hello World program
Primitives - Learn about the basic data types in Go
Flow Control - Controlling the flow of your program
Struct - All about struct
Functions - Define and call functions
Methods and Interfaces - Methods and interfaces in Go
Error Handling - Handling errors idiomatically
Concurrency - Goroutines and channels
Anti Patterns - Anti patterns in Go
Libraries - Standard library and third-party libraries
Testing - Writing unit tests with `go test`
Benchmarking - Performance benchmarks
Containerization - Dockerize your Go app
What's Next? - Explore the next steps in your Golang journey


Share to: