SoFunction
Updated on 2025-03-05

A brief discussion on strings and arrays in Go language

The string processing in go language is different from PHP and Java. First, declare strings and modify strings.

Copy the codeThe code is as follows:

package main
import "fmt"
var name string                                                                                                                             �
var empty name string = "" //Declare an empty string
func main() {
//Declare multiple strings and assign values
 a, b, v := "hello", "word", "widuu"
 (a, b, v)
//Convert the content of the string, first convert the type of a to []byte
 c := []byte(a)
//Assignment
 c[0] = 'n'
// When converting to string type, we actually found that our a has not changed
//But a new string change
 d := string(c)
 (d)
//Stand prototype output
 m := `hello
   word`
 (m)
}

How to declare arrays

Copy the codeThe code is as follows:

package main
import "fmt"
var arr [2]int //Declare an array
func main() {
arr[0] = 1 //Array assignment
 (arr)
arrtest := [3]int{1, 2, 3} //Another way to declare arrays
 (arrtest)
a := [...]int{1, 2} //[...] Automatically identify the length of the array
 (a)
(len(a))//The length of the output array
}

Below is the declaration and use of slice. This is actually a dynamic array.

Copy the codeThe code is as follows:

package main
import "fmt"
func main() {
d := []int{1, 2, 3} //Declare a slice, which is a dynamic array, has no length
 (d)
 var q, w []int
q = d[0:1] //The length above can be determined
 w = d[1:3]
d = append(d, 2) //Add elements to it
 (d)
 (q, w)
}