Go Basic Syntax
Go language has simple and clear syntax. This chapter will detail the basic syntax rules of Go language, including identifiers, keywords, literals, operators, and other core concepts.
🔤 Identifiers
Identifier Rules
Identifiers in Go are used to name variables, types, functions, etc.
Naming Rules
- Character Composition: Letters, numbers, underscores
- First Character: Must be a letter or underscore
- Case Sensitive:
nameandNameare different identifiers - Length Limit: No limit, but reasonable length is recommended
go
// Valid identifiers
var name string
var age int
var _private string
var userName string
var user_name string // Not recommended, Go style prefers camelCase
var π float64 // Supports Unicode characters
var 中文变量 string // Supports Chinese, but not recommended
// Invalid identifiers
// var 123name string // Cannot start with number
// var my-name string // Cannot contain hyphen
// var my name string // Cannot contain spaceNaming Conventions
Go Naming Conventions
go
// 1. Camel case (recommended)
var userName string // Small camel, used within package
var UserName string // Big camel, exported identifier
// 2. Constant naming
const MaxSize = 100 // Exported constant
const maxRetries = 3 // Package-internal constant
// 3. Function naming
func getName() string // Package-internal function
func GetName() string // Exported function
// 4. Type naming
type user struct // Package-internal type
type User struct // Exported type
// 5. Interface naming
type reader interface // Package-internal interface
type Reader interface // Exported interfaceVisibility Rules
go
package example
// Exported (accessible from other packages)
var PublicVar = "Public variable"
func PublicFunc() {}
type PublicType struct {}
// Package-internal (accessible only within current package)
var privateVar = "Private variable"
func privateFunc() {}
type privateType struct {}🔑 Keywords
Go Reserved Words
Go has 25 keywords that cannot be used as identifiers:
go
// Package and import
package import
// Declaration
var const type func
// Control flow
if else switch case default
for range break continue goto
return go select defer
// Type
chan interface map struct
// Other
fallthroughKeyword Categories
1. Declaration Keywords
go
package main // Package declaration
import "fmt" // Import declaration
var x int // Variable declaration
const PI = 3.14 // Constant declaration
type Point struct { X, Y int } // Type declaration
func hello() {} // Function declaration2. Control Flow Keywords
go
// Conditional control
if x > 0 {
fmt.Println("Positive")
} else {
fmt.Println("Non-positive")
}
// Multi-branch control
switch x {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
default:
fmt.Println("Other")
}
// Loop control
for i := 0; i < 10; i++ {
if i == 5 {
continue // Skip current iteration
}
if i == 8 {
break // Break out of loop
}
fmt.Println(i)
}
// Function return
func add(a, b int) int {
return a + b
}
// Unconditional jump (not recommended)
goto label
label:
fmt.Println("Jump here")3. Concurrency Keywords
go
// Start goroutine
go func() {
fmt.Println("Execute concurrently")
}()
// Channel operation
ch := make(chan int)
select {
case x := <-ch:
fmt.Println("Received:", x)
case ch <- 42:
fmt.Println("Sent successfully")
default:
fmt.Println("No available operation")
}
// Deferred execution
func example() {
defer fmt.Println("Execute at function end")
fmt.Println("Normal execution")
}💡 Literals
Numeric Literals
Integer Literals
go
// Decimal
var dec = 42
var dec2 = 1_000_000 // Can use underscores for readability
// Binary (Go 1.13+)
var bin = 0b1010 // Binary: 10
// Octal
var oct = 0o755 // Octal: 493
var oct2 = 0755 // Traditional octal notation
// Hexadecimal
var hex = 0xFF // Hexadecimal: 255
var hex2 = 0x2A // Hexadecimal: 42Floating-Point Literals
go
// Decimal form
var f1 = 3.14
var f2 = .25 // 0.25
var f3 = 1. // 1.0
// Scientific notation
var f4 = 1e6 // 1000000.0
var f5 = 2.5e-3 // 0.0025
var f6 = 1.5E+2 // 150.0
// Hexadecimal floating-point
var f7 = 0x1p-2 // 0.25 (1 * 2^-2)String Literals
Interpreted Strings
go
// Use double quotes, supports escape characters
var str1 = "Hello, World!"
var str2 = "First line\nSecond line"
var str3 = "Tab\tseparated"
var str4 = "Quote: \"content\""
var str5 = "Backslash: \\"Raw Strings
go
// Use backticks, does not process escape characters
var raw1 = `Hello, World!`
var raw2 = `First line
Second line` // Preserves newline
var raw3 = `File path: C:\Program Files\Go\bin`
var raw4 = `Regular expression: \d+\.\d+`Character Literals
go
// Use single quotes to represent characters (rune type)
var char1 = 'A' // Character A
var char2 = '中' // Chinese character
var char3 = '\n' // Newline character
var char4 = '\u4e2d' // Unicode: 中
var char5 = '\U00004e2d' // Unicode: 中
var char6 = '\x41' // Hexadecimal: ABoolean Literals
go
var true_val = true
var false_val = false📝 Syntax Structure
Statement Separation
go
// Go automatically inserts semicolons, usually no need to add manually
fmt.Println("First statement")
fmt.Println("Second statement")
// Multiple statements on same line require semicolon separation (not recommended)
x := 1; y := 2; z := x + y
// Braces cannot be placed on a new line alone (syntax requirement)
if x > 0 { // Correct
fmt.Println("Positive")
}
// if x > 0 // Wrong! Semicolon will be inserted automatically
// {
// fmt.Println("Positive")
// }Code Blocks
go
// Use braces to define code blocks
{
var x = 1
fmt.Println(x)
// x is only accessible within this code block
}
// fmt.Println(x) // Error! x is out of scope
// Function code block
func example() {
// Function body
}
// Conditional code block
if condition {
// if code block
} else {
// else code block
}🔧 Expressions and Operators
Arithmetic Operators
go
var a, b = 10, 3
fmt.Println(a + b) // 13 Addition
fmt.Println(a - b) // 7 Subtraction
fmt.Println(a * b) // 30 Multiplication
fmt.Println(a / b) // 3 Division (integer division)
fmt.Println(a % b) // 1 Remainder
// Floating-point division
var x, y = 10.0, 3.0
fmt.Println(x / y) // 3.3333333333333335Comparison Operators
go
var a, b = 5, 10
fmt.Println(a == b) // false Equal
fmt.Println(a != b) // true Not equal
fmt.Println(a < b) // true Less than
fmt.Println(a <= b) // true Less than or equal
fmt.Println(a > b) // false Greater than
fmt.Println(a >= b) // false Greater than or equalLogical Operators
go
var x, y = true, false
fmt.Println(x && y) // false Logical AND
fmt.Println(x || y) // true Logical OR
fmt.Println(!x) // false Logical NOT
fmt.Println(!y) // true Logical NOTBit Operators
go
var a, b uint = 12, 10 // Binary: 1100, 1010
fmt.Println(a & b) // 8 Bitwise AND: 1000
fmt.Println(a | b) // 14 Bitwise OR: 1110
fmt.Println(a ^ b) // 6 Bitwise XOR: 0110
fmt.Println(^a) // Bitwise NOT
fmt.Println(a << 2) // 48 Left shift: 110000
fmt.Println(a >> 2) // 3 Right shift: 11Assignment Operators
go
var x = 10
x += 5 // x = x + 5 Result: 15
x -= 3 // x = x - 3 Result: 12
x *= 2 // x = x * 2 Result: 24
x /= 4 // x = x / 4 Result: 6
x %= 5 // x = x % 5 Result: 1
// Bitwise assignment
x = 12 // Reset
x &= 10 // x = x & 10
x |= 5 // x = x | 5
x ^= 3 // x = x ^ 3
x <<= 1 // x = x << 1
x >>= 2 // x = x >> 2Increment/Decrement Operators
go
var i = 5
i++ // i = i + 1 Result: 6
i-- // i = i - 1 Result: 5
// Note: In Go, ++ and -- are statements, not expressions
// var j = i++ // Error! Cannot use this way
// var k = ++i // Error! Go has no pre-increment🎯 Operator Precedence
From highest to lowest priority:
| Priority | Operators | Description |
|---|---|---|
| 5 | * / % << >> & &^ | Multiplication, division, shift, bitwise AND |
| 4 | + - ` | ^` |
| 3 | == != < <= > >= | Comparison operators |
| 2 | && | Logical AND |
| 1 | ` |
Precedence Example
go
// Calculations with different priorities
result := 2 + 3 * 4 // 14 (3*4 calculated first)
result = (2 + 3) * 4 // 20 (use parentheses to change priority)
// Logical operator priority
condition := true || false && false // true (false && false calculated first)
condition = (true || false) && false // false (parentheses change priority)🔄 Type Inference
var Declaration Type Inference
go
// Explicit type specification
var name string = "Go"
var age int = 10
// Type inference
var name2 = "Go" // Inferred as string
var age2 = 10 // Inferred as int
var pi = 3.14 // Inferred as float64
var isTrue = true // Inferred as boolShort Variable Declaration
go
// Use := for declaration and initialization
name := "Go" // string
age := 25 // int
height := 1.75 // float64
isStudent := false // bool
// Multiple variable declaration
x, y := 10, 20
a, b, c := 1, 2.5, "hello"📋 Blank Identifier
Discarding Unused Values
go
// When function returns multiple values, use _ to discard unused values
value, _ := strconv.Atoi("123") // Ignore error
_, err := fmt.Println("Hello") // Ignore returned byte count
// Import package but don't use (only execute init function)
import _ "net/http/pprof"
// Check if type implements interface
var _ io.Writer = (*os.File)(nil)🎯 Practical Example
Comprehensive Syntax Example
go
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func main() {
// Variable declaration and type inference
var message string = "Hello, Go!"
count := 42
pi := 3.14159
isActive := true
// String operations
fmt.Println("Original message:", message)
fmt.Println("Uppercase:", strings.ToUpper(message))
fmt.Println("Length:", len(message))
// Numeric operations
fmt.Printf("Number: %d, Square: %d\n", count, count*count)
fmt.Printf("π ≈ %.2f, Area: %.2f\n", pi, pi*math.Pow(5, 2))
// Conditional judgment
if count > 40 {
fmt.Println("count greater than 40")
}
// Type conversion
countStr := strconv.Itoa(count)
fmt.Println("Number to string:", countStr)
// Operator demonstration
a, b := 15, 4
fmt.Printf("%d + %d = %d\n", a, b, a+b)
fmt.Printf("%d - %d = %d\n", a, b, a-b)
fmt.Printf("%d * %d = %d\n", a, b, a*b)
fmt.Printf("%d / %d = %d\n", a, b, a/b)
fmt.Printf("%d %% %d = %d\n", a, b, a%b)
// Bit operation demonstration
x, y := uint(12), uint(10)
fmt.Printf("Bit AND: %d & %d = %d\n", x, y, x&y)
fmt.Printf("Bit OR: %d | %d = %d\n", x, y, x|y)
fmt.Printf("Bit XOR: %d ^ %d = %d\n", x, y, x^y)
// Logical operations
fmt.Printf("true && false = %t\n", true && false)
fmt.Printf("true || false = %t\n", true || false)
fmt.Printf("!true = %t\n", !true)
}🎓 Summary
In this chapter, we learned the basic syntax of Go language:
- ✅ Identifiers: Naming rules and visibility standards
- ✅ Keywords: 25 reserved words and their uses
- ✅ Literals: Numeric, string, character, boolean literals
- ✅ Operators: Arithmetic, comparison, logical, bitwise, assignment operators
- ✅ Syntax Structure: Statement separation, code blocks, expressions
- ✅ Type Inference: Automatic type inference mechanism
Mastering these basic syntaxes is an important foundation for further learning Go.
Next, we will learn Go Data Types to deeply understand Go's type system.
Syntax Tips
- Go language syntax is designed to be simple and clear, reducing unnecessary complexity
- Brace placement has strict requirements, left brace cannot be on a new line alone
- Use gofmt tool to automatically format code and maintain consistent code style