Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Go Syntax Fundamentals

4. Go Syntax Fundamentals

1. Package Declaration:

In Go, every source file belongs to a package. The 'package' declaration should be the first line of your source file. It defines the package name to which the file belongs.

Example:
 
package main

 

2.Import Statements:

Import statements are used to bring external packages into your code. Imported packages provide functions, types, and variables that you can use in your program.

Example:
import "fmt"

 

3. Function Declaration:

Functions are the building blocks of a Go program. They are defined using the 'func' keyword, followed by the function name, parameter list, return type, and function body.
 
Example:
func add(a, b int) int {
return a + b
}

 

4. Variables and Constants:

Variables are used to store values that can change during program execution, while constants are used for values that remain unchanged.

Example:
var x int = 5
const pi = 3.14159

 

5. Data Types:

Go has several basic data types, including integers, floats, strings, and booleans. You can also define your own custom types using structs.

Example:
var age int = 25
var name string = "Alice"
type Point struct {
X, Y int
}

 

6. Control Flow Statements:

Go supports common control flow statements like 'if', 'for', and 'switch'.

if x > 0 {
fmt.Println("Positive")
} else {
fmt.Println("Non-positive")
}

for i := 0; i < 5; i++ {
fmt.Println(i)
}

switch day {
case "Monday":
fmt.Println("It's the start of the week.")
case "Friday":
fmt.Println("It's almost the weekend!")
default:
fmt.Println("It's another day.")
}

 

7. Comments:

Comments are used to add explanations or notes to your code. Single-line comments start with  '//', and multi-line comments are enclosed in '/* ... */'.

Example:
// This is a single-line comment.

/*
This is a
multi-line comment.
*/

 

8. Print Statements:

You can use the 'fmt' package to print formatted output to the console.

Example:
 fmt.Println("Hello, Go!")

 

These are some fundamental aspects of Go's syntax. By mastering these elements, you'll be well-equipped to write clear and functional Go programs. As you delve deeper into Go, you'll encounter more advanced features and concepts that build upon these syntax fundamentals.