Golang Tour-A string of data types

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Background

Learning Go has been a long time, for its data type has not been more in-depth understanding, here to do a summary of the data type, the first is the introduction of the string.

Strings in the Golang

func stringDemo() {    str := "李阳"    //len函数返回的是字节长度    fmt.Println(len(str))    //utf8的RuneCountInString判断的是ASCII长度    fmt.Println(utf8.RuneCountInString(str))}

string concatenation

In Java, what do we usually do with concatenation of strings? With the plus sign splicing, with StringBuffer, with StringBuilder. There are several ways to go, each with a different performance.

string concatenation via +

In the go language, the storage structure of string in memory is a fixed-length byte array, which means that the string is immutable. When you want to modify a string, you need to convert it to []byte, and then convert it back after the modification is complete. However, no matter how you convert, you must reallocate the memory and copy the data.

func appendStrUsePlus() {    var s1 = "Hello "    var s2 = "World"    s3 := s1 + s2    fmt.Println(s3)}

The string is spliced with a plus sign, and memory must be redistributed each time. So if it is frequently used + splicing there will be serious performance problems. How to solve it? The idea is: pre-allocating large enough memory space, which is what we're going to say next strings. The Join () method, which counts the length of all parameters and completes the memory allocation operation once.

Stitching via Strings.join ()

Using the methods in strings, you need to introduce the strings library.

func appendStrUseJoin() {    s := make([]string, 10)    for i := 0; i < 10; i++ {        s[i] = "h"    }    fmt.Println(strings.Join(s, ","))//h,h,h,h,h,h,h,h,h,h}

Look at string. The source of the join (), the first parameter is an array of strings, the second parameter is a delimiter, a bit like the Join method in Java StringUtils.

func Join(a []string, sep string) string {    if len(a) == 0 {        return ""    }    if len(a) == 1 {        return a[0]    }    n := len(sep) * (len(a) - 1)    for i := 0; i < len(a); i++ {        n += len(a[i])    }    b := make([]byte, n)    bp := copy(b, a[0])    for _, s := range a[1:] {        bp += copy(b[bp:], sep)        bp += copy(b[bp:], s)    }    return string(b)}

Assemble and splice via buffer

Using buffer is a priority to create a buffer and then write data to the buffer, similar to StringBuffer in Java.

func appendStrUseBuf() {    var b bytes.Buffer    b.Grow(100)    for i := 0; i < 100; i++ {        b.WriteString("a")    }    fmt.Println(b.String())}

String segmentation

In Java we have the Stringutils.split () method, and there is a similar approach in go: Strings.split ().

func splitStr() {    str := "liyang,liyang,liyang"    strs := strings.Split(str, ",")    fmt.Println(strs)}

In addition there are SPLITN (), Splitafter (), Spliteaftern () methods, but are not particularly commonly used.

String interception

The string is actually a byte array, so we can intercept the string by way of a shard.

String to byte array

First, let's look at a piece of code, which we've mentioned before, that the string is actually a byte array, so we can manipulate each byte of the string like an array of operations.

func strConsole() {    str := "liyang"    for i := 0; i < len(str); i++ {        fmt.Println(string(str[i]))    }}

String Default value

The string default is an empty string, not nil.

func stringDefaultVal() {var str stringfmt.Println(str == nil) //invalid operation: str == nil (mismatched types string and nil)fmt.Println(str == "")}

String storage structure

In Java, strings are stored in a char array, so the string is immutable. So how are strings stored in the go language? In go, a string is an immutable array of bytes whose head pointer points to a byte array.

String memory allocation

The string defaults to allocating memory storage on the heap.

Related Article

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.