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.
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
}
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".