Golang String Conversion Array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.