Syntax in Golang

In Go, the syntax is the set of rules that define how a Go program is written and organized. Here are a few examples of Go syntax:

Declaring variables:

// Declare a variable of type int with the identifier "x"
var x int

// Declare a variable of type string with the identifier "message" and initialize it to a string literal
var message string = "hello world"

// Declare a variable of type bool with the identifier "isTrue" and initialize it to the value true
var isTrue bool = true

// Declare multiple variables at once
var x, y, z int
var message string = "hello"
var isTrue bool = true

Declaring constants:

// Declare a constant of type int with the identifier "maxValue" and initialize it to the value 100
const maxValue int = 100

// Declare multiple constants at once
const x, y, z = 1, 2, 3
const message = "hello"
const isTrue = true

Declaring functions:

// Declare a function called "add" that takes two int arguments and returns their sum as an int
func add(x int, y int) int {
    return x + y
}

// Declare a function called "sayHello" that takes no arguments and returns a string
func sayHello() string {
    return "Hello!"
}

Using control structures:

// Use an if statement to conditionally execute a block of code
if x > 0 {
    // ...
}

// Use a for loop to iterate over a range of values
for i := 0; i < 10; i++ {
    // ...
}

// Use a switch statement to select from multiple branches of code
switch x {
case 0:
    // ...
case 1:
    // ...
default:
    // ...
}

Defining types:

// Define a new type called "Person" with two fields: "Name" (a string) and "Age" (an int)
type Person struct {
    Name string
    Age  int
}

// Define a method on the Person type called "sayHello" that takes no arguments and returns a string
func (p Person) sayHello() string {
    return "Hello, my name is " + p.Name
}