Golang byte-to-byte array-to-string problem

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

Golang language itself is a tool set of C, the development of C programs used by most of the structure, memory management, Ctrip and so on, Golang basically have, he just on this basis added some concepts here to say a very small problem, is a byte array to string problem, Most of the internet is like this (including Google):string(P[:]), this turn over is a problem, Let's take a look at the structure of string:

struct String
{
byte* str;
Intgo Len;
};

This structure reminds me of the Nginx string, which he defines:

typedef struct {
size_t Len;
U_char *data;
} ngx_str_t;

Golang inside the concept of string is actually not encountered before the concept of the end, he is actually a continuous memory, the first address + length, the above assignment, if p inside has, he will not do this time, if the string to do other processing may be a problem, Like StrConv. Atoi to int there is an error, the solution is to write a formal conversion function:

Func byteString (P []byte) string {
For I: = 0; i < Len (p); i++ {
If p[i] = = 0 {
return string (P[0:i])
}
}
return string (p)
}

So it won't be a problem.

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.