Introduction to the Go Programming Language — part 1
Go, often known as Golang, is a contemporary and adaptable programming language that has been more well-known since its release in 2007. Go was developed by Google employees Ken Thompson, Rob Pike, and Robert Griesemer with an emphasis on productivity for developers. It was developed in response to the demand for a language that could improve upon the drawbacks of already existing languages and provide a solid foundation for creating scalable and high-performance applications.
Go’s unique characteristics and objectives served as a catalyst for its entry to the programming world. It was designed to be a statically typed language with clear syntax that is simple to understand and write. To allow developers to remain productive without compromising performance, the creators of Go worked to mix simplicity and power.
The powerful concurrency support provided by Go’s goroutines and channels is one of the language’s distinguishing features. With the help of this concurrent programming paradigm, programmers may effectively build concurrent and parallel code while reducing the difficulties often brought on by threading and synchronization.
Go also has a robust standard library that spans a variety of topics, from system-level work to network programming and web development. Its reputation as a language ideal for constructing everything from web servers and microservices to command-line utilities and system software has been aided by its package management system, integrated testing framework, and great tools.
Furthermore, Go has grown significantly in popularity, becoming the language of choice for cloud-native and containerized projects like Docker and Kubernetes. It is a great option for developing containerized apps and microservices because to its speed, efficiency, and tiny binary size.
Creation the first Go program
You can find the installation files at click here.
Observe the guidelines specific to your operating system. Run the following command in a terminal window to see whether Go was successfully installed:
go version
- Launch the VS Code editor (donwload from here)
- Open the extension manager or alternatively, press Ctrl + Shift + x
- In the search box, type “go” and hit enter
- Find the Go extension by the GO team at Google and install the extension
- After the installation is complete, open the command palette by pressing Ctrl + Shift + p
- Run the Go: Install/Update Tools command
- Select all the provided tools and click OK
VS Code is now configured to use Go.
8. Open up a terminal window and type:
go mod init example.com/hello
9. Create a new file. Copy and paste the following code and save the file as helloworld.go:
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
}
10. Open a terminal in VS Code and type:
go run .\helloworld.go
Go Comments
- Single-line comments start with two forward slashes (
//
):
// This is a comment
package main
import ("fmt")
func main() {
// This is a comment
fmt.Println("Hello World!")
}
2. Multi-line Comments(//
):
package main
import ("fmt")
func main() {
/* The code below will print Hello World
to the screen, and it is amazing */
fmt.Println("Hello World!")
}
Declaring Variables
- Use the
var
keyword, followed by variable name and type:
var variablename type = value
// 1. You always have to specify either type or value (or both).
// 2. Can be used inside and outside of functions.
// 3. Variable declaration and value assignment can be done separately.
2. Use the :=
sign, followed by the variable value:
variablename := value
// 1. the compiler decides the type of the variable, based on the value.
// 2. It is not possible to declare a variable using :=,
// without assigning a value to it.
// 3. Can only be used inside functions.
// 4. Variable declaration and value assignment must be done in the same line
Variable Declaration With Initial Value
package main
import ("fmt")
func main() {
var student1 string = "John" //type is string
var student2 = "Jane" //type is inferred
x := 2 //type is inferred
fmt.Println(student1)
fmt.Println(student2)
fmt.Println(x)
}
/*
result:
_______________
John
Jane
2
_______________
*/
Variable Declaration Without Initial Value
All variables in Go are initialized. Therefore, if a variable is declared without an initial value, its value will be set to the type’s default value:
package main
import ("fmt")
func main() {
var a string
var b int
var c bool
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
/*
result:
_______________
""
0
false
_______________
*/
Multiple Variable Declaration
package main
import ("fmt")
func main() {
var a, b, c, d int = 1, 3, 5, 7
// If you use the type keyword, it is only possible to
// declare one type of variable per line.
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
/*
result:
_______________
1
3
5
7
_______________
*/
If the type
keyword is not specified, you can declare different types of variables in the same line:
package main
import ("fmt")
func main() {
var a, b = 6, "Hello"
c, d := 7, "World!"
// If the type keyword is not specified, you can declare different
// types of variables in the same line.
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
/*
result:
_______________
6
Hello
7
World!
_______________
*/
package main
import ("fmt")
func main() {
var (
a int
b int = 1
c string = "hello"
)
// Multiple variable declarations can also be grouped together
// into a block for greater readability:
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
/*
result:
_______________
0
1
hello
_______________
*/
Go variable naming rules
1. A variable name must start with a letter or an underscore character (_).
2. A variable name cannot start with a digit.
3. A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0–9, and _ ).
4. Variable names are case-sensitive (age, Age and AGE are three different variables).
5. There is no limit on the length of the variable name.
6. A variable name cannot contain spaces.
7. The variable name cannot be any Go keywords.
package main
import ("fmt")
func main() {
var (
myVariableName string = "John"
MyVariableName string = "John"
my_variable_name string = "John"
)
fmt.Println(myVariableName)
fmt.Println(MyVariableName)
fmt.Println(my_variable_name)
}
/*
result:
_______________
John
John
John
_______________
*/
Constants
const CONSTNAME type = value
// The value of a constant must be assigned when you declare it.
// When a constant is declared, it is not possible to change the value later.
package main
import ("fmt")
const PI = 3.14
func main() {
fmt.Println(PI)
}
/*
result:
_______________
3.14
_______________
*/
- Typed constants:
package main
import ("fmt")
const A int = 1
func main() {
fmt.Println(A)
}
/*
result:
_______________
1
_______________
*/
2. Untyped constants:
package main
import ("fmt")
const A = 1
func main() {
fmt.Println(A)
}
/*
result:
_______________
1
_______________
*/
3. Multiple Constants Declaration
package main
import ("fmt")
const (
A int = 1
B = 3.14
C = "Hi!"
)
func main() {
fmt.Println(A)
fmt.Println(B)
fmt.Println(C)
}
/*
result:
_______________
1
3.14
Hi!
_______________
*/
Output Functions
Print()
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i, "\n")
fmt.Print(j, "\n")
// or use fmt.Print(i, "\n", j)
// Print inserts a space between the arguments if neither are strings.
}
/*
result:
_______________
Hello
World
_______________
*/
2. Println()
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Println(i,j)
}
/*
result:
_______________
Hello World
_______________
*/
3. Printf()
first formats its argument based on the given formatting verb and then prints them.
package main
import ("fmt")
func main() {
var i = 15.5
var txt = "Hello World!"
fmt.Printf("%v\n", i)
fmt.Printf("%#v\n", i)
fmt.Printf("%v%%\n", i)
fmt.Printf("%T\n", i)
fmt.Printf("%v\n", txt)
fmt.Printf("%#v\n", txt)
fmt.Printf("%T\n", txt)
// %v Prints the value in the default format
// %#v Prints the value in Go-syntax format
// %T Prints the type of the value
// %% Prints the % sign
}
/*
result:
_______________
15.5
15.5
15.5%
float64
Hello World!
"Hello World!"
string
_______________
*/
package main
import ("fmt")
func main() {
var i = 15
fmt.Printf("%b\n", i)
fmt.Printf("%d\n", i)
fmt.Printf("%+d\n", i)
fmt.Printf("%o\n", i)
fmt.Printf("%O\n", i)
fmt.Printf("%x\n", i)
fmt.Printf("%X\n", i)
fmt.Printf("%#x\n", i)
fmt.Printf("%4d\n", i)
fmt.Printf("%-4d\n", i)
fmt.Printf("%04d\n", i)
// %b Base 2
// %d Base 10
// %+d Base 10 and always show sign
// %o Base 8
// %O Base 8, with leading 0o
// %x Base 16, lowercase
// %X Base 16, uppercase
// %#x Base 16, with leading 0x
// %4d Pad with spaces (width 4, right justified)
// %-4d Pad with spaces (width 4, left justified)
// %04d Pad with zeroes (width 4)
}
/*
result:
_______________
1111
15
+15
17
0o17
f
F
0xf
15
15
0015
_______________
*/
package main
import ("fmt")
func main() {
var txt = "Hello"
fmt.Printf("%s\n", txt)
fmt.Printf("%q\n", txt)
fmt.Printf("%8s\n", txt)
fmt.Printf("%-8s\n", txt)
fmt.Printf("%x\n", txt)
fmt.Printf("% x\n", txt)
// %s Prints the value as plain string
// %q Prints the value as a double-quoted string
// %8s Prints the value as plain string (width 8, right justified)
// %-8s Prints the value as plain string (width 8, left justified)
// %x Prints the value as hex dump of byte values
// % x Prints the value as hex dump with spaces
}
/*
result:
_______________
Hello
"Hello"
Hello
Hello
48656c6c6f
48 65 6c 6c 6f
_______________
*/
package main
import ("fmt")
func main() {
var i = true
var j = false
fmt.Printf("%t\n", i)
fmt.Printf("%t\n", j)
// %t Value of the boolean operator in true or false
// format (same as using %v)
}
/*
result:
_______________
true
false
_______________
*/
package main
import ("fmt")
func main() {
var i = 3.141
fmt.Printf("%e\n", i)
fmt.Printf("%f\n", i)
fmt.Printf("%.2f\n", i)
fmt.Printf("%6.2f\n", i)
fmt.Printf("%g\n", i)
// %e Scientific notation with 'e' as exponent
// %f Decimal point, no exponent
// %.2f Default width, precision 2
// %6.2f Width 6, precision 2
// %g Exponent as needed, only necessary digits
}
/*
result:
_______________
3.141000e+00
3.141000
3.14
3.14
3.141
_______________
*/
Data Types
1. bool: represents a boolean value and is either true or false.
2. Numeric: represents integer types, floating point values, and complex types.
3. string: represents a string value.
package main
import ("fmt")
func main() {
var a bool = true // Boolean
var b int = 5 // Integer
var c float32 = 3.14 // Floating point number
var d string = "Hi!" // String
fmt.Println("Boolean: ", a)
fmt.Println("Integer: ", b)
fmt.Println("Float: ", c)
fmt.Println("String: ", d)
}
/*
result:
_______________
Boolean: true
Integer: 5
Float: 3.14
String: Hi!
_______________
*/
1. Boolean:
package main
import ("fmt")
func main() {
var b1 bool = true
var b2 = true
var b3 bool
b4 := true
fmt.Println(b1)
fmt.Println(b2)
fmt.Println(b3)
fmt.Println(b4)
}
/*
result:
_______________
true
true
false
true
_______________
*/
2. Integers:
package main
import ("fmt")
func main() {
var x int = 500
var y int = -4500
// int keywords, can store both positive and negative values.
fmt.Printf("Type: %T, value: %v", x, x)
fmt.Printf("Type: %T, value: %v", y, y)
}
/*
result:
_______________
Type: int, value: 500
Type: int, value: -4500
_______________
*/
package main
import ("fmt")
func main() {
var x uint = 500
var y uint = 4500
// uint keywords, can only store non-negative values.
fmt.Printf("Type: %T, value: %v", x, x)
fmt.Printf("Type: %T, value: %v", y, y)
}
/*
result:
_______________
Type: uint, value: 500
Type: uint, value: 4500
_______________
*/
3. Float:
The default type for float is float64
.
package main
import ("fmt")
func main() {
var x float32 = 123.78
var y float32 = 3.4e+38
fmt.Printf("Type: %T, value: %v\n", x, x)
fmt.Printf("Type: %T, value: %v", y, y)
}
/*
result:
_______________
Type: float32, value: 123.78
Type: float32, value: 3.4e+38
_______________
*/
package main
import ("fmt")
func main() {
var x float64 = 1.7e+308
fmt.Printf("Type: %T, value: %v", x, x)
}
/*
result:
_______________
Type: float64, value: 1.7e+308
_______________
*/
4. String:
package main
import ("fmt")
func main() {
var txt1 string = "Hello!"
var txt2 string
txt3 := "World 1"
fmt.Printf("Type: %T, value: %v\n", txt1, txt1)
fmt.Printf("Type: %T, value: %v\n", txt2, txt2)
fmt.Printf("Type: %T, value: %v\n", txt3, txt3)
}
/*
result:
_______________
Type: string, value: Hello!
Type: string, value:
Type: string, value: World 1
_______________
*/
That’s enough for this article. In the next one all of Arrays, Slices, Operators, Conditions, Switch, Loops, Functions, Struct and Maps will discussed.