- vừa được xem lúc

[ENG] Golang: Part 2 - Basic syntax, constants, variables, data types and control statements

0 0 8

Người đăng: PHAM HIEU

Theo Viblo Asia

After reading the previous article, we have gained knowledge about Golang and learned how to install and compile code using Go. In this article, I will guide you through becoming familiar with the syntax, data types, and variable declarations when working with Golang. Let's get started.

I used to write that "Go is quite easy to write, especially compared to C, C++, Java; it's much easier." Indeed, it's remarkably straightforward to work with. The following are the basic syntax elements in Go: Package declaration, importing packages, functions, statements and expressions, comments, variables, data types, and arrays. All of these will be demonstrated in this article.

Basic syntax

In the previous part [ENG] Golang: Part 1 - Installation and Introduction , we learned how to print 'Hello, world' to the screen. Let's review it:

package main import "fmt" func main() { fmt.Println("Hello, world!")
}

Look at the code above, the first line, package main, is used to declare a package named "main".The second line imports a package for our program. The last line demonstrates how to declare a function using func main () {}. We dont need to use semicolons after fmt.Println("Hello, world!") Because Go can insert semicolon automatically after every statementThis is similar to Python's syntax. Additionally, you can insert semicolons directly at the end of a statement, and your program will still work correctly.

However, it's important to note that you cannot place the opening brace of a control structure (such as if, for, switch, select) on the next line, as this will cause the insertion of a semicolon at the end of the if statement. For example:

if i < f() //wrong!, it's will insert automatically semicolon at the end of this line.
{ g()
}

To avoid this issue, you should declare it as follows:

if i < f() { g()
}

This ensures proper handling of control structures in Go.

Constants, Variables, data types:

Constants

Like others programing languages, constants in Go is a value that does not change during the execution of a program. Constant variables are typically used to define fixed values that should not be altered after thay are declared. To declare a constant variable in Go, you use the const keyword, followed by the constant's name and its value. For example:

const pi = 3.14
const appURL = "https://viblo.asia"

Variables

In the Golang, we can declare variable by using the var keywords followed by the variable name and its data type. For example:

var name string
var username string
var id int

We can also initialize a variable when we declare it. Go can automatically infer the variable's type from the init values:

var name = "Pham Hieu" //string
var username = "pviethieu" //string
var id = 123 //int

Or we can use := operator for short variable declarations. This way, you can declare and init a variable in the same line.

name := "Pham Hieu"
username := "pviethieu"
id := 123

We can declare multiple variables at once by following example:

var ( name string username string id string
)

Also short declare with multiple variables :

name, username, id := "Pham Hieu", "pviethieu", 123

Variables in Go have block-level scope, meaning they are only accessible within the block where they are declared. Futhermore, if a variable is declared but not explicitly initialized, it will be set to its "zero value" (0 for numeric types, false for the boolean type, empty string "" for strings)

Data types

For make program clearly and ensure performance of executing. We need to know exactly which data type we used. Go also has data types like the other languages. Go's data types are:

  1. Numeric Types:

    • int: Signed integer type. Its size depends on the platform (32 or 64 bits).
    • int8, int16, int32, int64: Signed integers of specific sizes.
    • uint: Unsigned integer type, platform-dependent.
    • uint8, uint16, uint32, uint64: Unsigned integers of specific sizes.
    • float32: 32-bit floating-point number.
    • float64: 64-bit floating-point number.
    • complex64: Complex number with float32 real and imaginary parts.
    • complex128: Complex number with float64 real and imaginary parts.
  2. Boolean Type:

    • bool: Represents a boolean value, either true or false.
  3. Character Types:

    • byte: An alias for uint8, used to represent a single byte.
    • rune: An alias for int32, used to represent a Unicode code point (a character).
  4. String Type:

    • string: Represents a sequence of characters. Go strings are immutable.
  5. Composite Types:

    • array: A fixed-size collection of elements of the same type.
    • slice: A dynamic, resizable collection built on top of arrays.
    • map: A collection of key-value pairs, where keys are unique.
    • struct: A composite data type that groups together variables of different types under a single name.
    • interface: A type that defines a set of method signatures, used for polymorphism.
  6. Pointer Types:

    • pointer: A type that holds the memory address of another value.
  7. Function Types:

    • func: Represents a function.
  8. Channel Types:

    • chan: Used for communication between goroutines in Go's concurrency model.
  9. Type Aliases:

    • You can create type aliases in Go to provide alternative names for existing data types.

Example usage:

var num int
var price float64
var isValid bool
var char rune
var name string
var scores [5]int
var grades []string
var person struct { FirstName string LastName string Age int
}
var employeeMap map[string]int
var add func(int, int) int
var ch chan string

Control statement:

For

Compared to other languages, Go has a different approach and has only one looping construct, the for loop:

 sum := 1 for i:=0; i < 1000; i+=1 { sum += i }

If you want to use a while loop, similar to C or PHP, you can omit the semicolons and place the condition after the for statement:

	sum := 1 for sum < 1000 { sum += sum }

To iterate over elements of data structures like arrays, slices, maps, and strings, you can use the range keyword in a for loop. For example:

for index, user := range users { // Code to process each user in the users collection
}

Go also has if and switch statements:

If

if a > b { return a // return max of two numbers
}

Switch

status := "pending"
switch status { case 'new': return 1 case 'approve': return 2 case 'pending': return 3 default: return 0
}

Note that you cannot declare an expression after switch if it's in a function. Also, you can combine conditions in a case statement, for example:

func unhex(c byte) byte { switch { case '0' <= c && c <= '9': return c - '0' case 'a' <= c && c <= 'f': return c - 'a' + 10 case 'A' <= c && c <= 'F': return c - 'A' + 10 } return 0
}

You can use multiple conditions by using comma-separated lists in a case statement:

func shouldEscape(c byte) bool { switch c { case ' ', '?', '&', '=', '#', '+', '%': return true } return false
}

For more knowlegde, we can follow this instruction: https://go.dev/doc/effective_go#switch

Summary

In summary, this article provides a beginner-friendly introduction to Golang, emphasizing its simplicity and practicality. It covers fundamental syntax, variable and data type handling, and control structures. With this foundation, readers are well-prepared to dive into Golang programming, making it a valuable resource for those looking to explore this versatile and efficient language. Thank you for following along to the end of this article. If you feel that helpful for yourself, please consider leaving a vote for my article. Thank you and see you in the next part.

Bình luận

Bài viết tương tự

- vừa được xem lúc

gRPC - Nó là gì và có nên sử dụng hay không?

Nhân một ngày rảnh rỗi, mình ngồi đọc lại RPC cũng như gRPC viết lại để nhớ lâu hơn. Vấn đề là gì và tại sao cần nó .

0 0 112

- vừa được xem lúc

Embedded Template in Go

Getting Start. Part of developing a web application usually revolves around working with HTML as user interface.

0 0 40

- vừa được xem lúc

Tạo Resful API đơn giản với Echo framework và MySQL

1. Giới thiệu.

0 0 44

- vừa được xem lúc

Sử dụng goquery trong golang để crawler thông tin các website Việt Nam bị deface trên mirror-h.org

. Trong bài viết này, mình sẽ cùng mọi người khám phá một package thu thập dữ liệu có tên là goquery của golang. Mục tiêu chính của chương trình crawler này sẽ là lấy thông tin các website Việt Nam bị deface (là tấn công, phá hoại website, làm thay đổi giao diện hiển thị của một trang web, khi người

0 0 218

- vừa được xem lúc

Tạo ứng dụng craw dữ liệu bing với Golang, Mysql driver

Chào mọi người . Lâu lâu ta lại gặp nhau 1 lần, để tiếp tục series chia sẻ kiến thức về tech, hôm nay mình sẽ tìm hiểu và chia sẻ về 1 ngôn ngữ đang khá hot trong cộng đồng IT đó là Golang.

0 0 59

- vừa được xem lúc

Golang: Rest api and routing using MUX

Routing with MUX. Let's create a simple CRUD api for a blog site. # All . GET articles/ .

0 0 39