reCAPTCHA WAF Session Token
Go

From Basics to Advanced: Go Programming Language Examples

The Go programming language, also known as Golang, has gained popularity among developers for its simplicity, performance, and concurrency support. Whether you are a beginner looking to learn the basics of Go or an experienced developer looking to advance your skills, this article will provide you with examples ranging from basic to advanced.

1. Hello World: The classic “Hello World” program is often the first program beginners write in any programming language. In Go, it looks like this:

“`go

package main

import “fmt”

func main() {

fmt.Println(“Hello, World!”)

}

“`

This simple program imports the “fmt” package, which provides functions for formatting input and output, and prints the string “Hello, World!” to the console.

2. Variables and Constants: In Go, you can declare variables using the `var` keyword and constants using the `const` keyword. Here’s an example:

“`go

package main

import “fmt”

func main() {

var message string = “Hello, Go!”

fmt.Println(message)

const pi float64 = 3.14159

fmt.Println(pi)

}

“`

3. Functions: Functions in Go are declared using the `func` keyword. Here’s an example of a simple function that takes two integers as input and returns their sum:

“`go

package main

import “fmt”

func add(x, y int) int {

return x + y

}

func main() {

result := add(3, 5)

fmt.Println(result)

}

“`

4. Structs and Methods: Go supports object-oriented programming through the use of structs and methods. Here’s an example of a struct representing a person with a method to greet them:

“`go

package main

import “fmt”

type Person struct {

Name string

Age int

}

func (p Person) greet() {

fmt.Println(“Hello, my name is”, p.Name, “and I am”, p.Age, “years old.”)

}

func main() {

person := Person{Name: “Alice”, Age: 30}

person.greet()

}

“`

5. Concurrency: One of Go’s key features is its support for concurrency through goroutines and channels. Here’s an example of a simple program that uses goroutines to print numbers concurrently:

“`go

package main

import “fmt”

func printNumbers() {

for i := 1; i

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button
WP Twitter Auto Publish Powered By : XYZScripts.com
SiteLock