In Golang, there are two types of arrays and slices. A slice is a reference type, and an array is a value type. If you want to pass in a pointer parameter to an array in a function, you must specify the number of arrays, as
Func Stringtorunearr (S string, arr *[5]rune) If you remove 5 from arr *[5]rune, it means that the parameter becomes a slice type, the pointer to the array is not passed in, the compilation will be error, then must write the length of the dead array? This is too not elegant. After a search, it is found that the method is very simple, that is, the parameters of the function to slice, and then pass the array of slices in. Because the slice is a reference type, the actual modification in the function is the corresponding original array, thus achieving the purpose of modifying the array, as long as the modification does not exceed the length of the array, there is no problem. The code example is as follows:
func Stringtorunearr (s string arr []rune) {src: = []rune (s) for i, V: = range src { if i >= Len (arr) { break } Arr[i] = v}}func Main () {str: = This is a string abcdef
" var arr [10 ]rune utility. Stringtorunearr (str, arr[:]) fmt. Println ( string (arr[:])}
Output This is a string ABC