当前位置:网站首页>Go questions / knowledge gathering - 2

Go questions / knowledge gathering - 2

2022-06-09 08:01:00 A boy in plain white

1. Application scenarios  

Mainly used to collect Go Knowledge , Temporary storage .

2. Study / operation

1. Document reading

source code

https://github.com/bigwhite/publication

12| Basic data type :Go What are the natively supported numeric types ?- Geek time

13| Basic data type : Why? Go To natively support string types ?- Geek time

2. Organize output

------------------------------------------------------------ Separator ------------------------------------------------------------

12| Basic data type :Go What are the natively supported numeric types ?- Geek time

1. Net friend - Roger

float It's actually quite complicated , If you can avoid it in development, you can avoid it , For example, the monetary unit is only US dollars or RMB. I suggest using cents as the unit .

The author replied : Um. , That's true .

2. Net friend -liaomars
var f1 float32 = 16777216.0
var f2 float32 = 16777217.0
f1 == f2 // true

f1 Convert to binary yes :1266679808
f2 Converting to binary is also :1266679808
Why is this equal , Because the data converted to binary is equal .

The author replied :

3. Net friend - Sheep and sheep

0x1.Fp+0 // 1.9375 * 2^0 = 1.937500 How is this calculated ?0x1.F=1.9375 How to get it ?

The author replied : 0x1.Fp+0 Medium F It's a hexadecimal number , Its decimal value is 15.F One place after the decimal point , So the decimal part of the number above 0.F Convert to 10 Base decimals are 15 x 16^(-1)=0.9375 --- Personal supplement : Same as decimal conversion

4. Net friend -qinsi ---- I don't understand very much for the time being , Continue to learn , understand  --- Calm down

16777216.0 = 2^24 = (1+.0) * 2^24
because float32 The mantissa of is only 23bit, The next number that can be represented is (1+2^(-23))*2^24 = 2^24+2 = 16777218.0
and 16777217.0 = 2^24 + 1 = (1+2^(-24)) * 2^24, The mantissa must be 2^(-24), need 24bit To express

Intuitively understood words , Real numbers are infinite , The binary representation of floating point numbers is finite , So there must be real numbers that cannot be represented by floating-point numbers . Mark the floating point number on the real number axis , There are holes between adjacent floating-point numbers . And as the index increases , The hole between adjacent floating-point numbers will become larger and larger . For example, for float32 Come on ,2^24+1 Is the first integer to fall on such a hole . And from 2^25 Start , The next number that can be represented is (1+2^(-23))*2^25 = 2^25 + 4, There will be 3 An integer cannot represent .

Empathy , about float64 The first integer that cannot be represented is 2^53+1( Because the mantissa is only 52bit):

```go
f1 := 9_007_199_254_740_992.0
f2 := 9_007_199_254_740_993.0
fmt.Println(f1 == f2)
```

(js Programmers say this is greater than Number.MAX_SAFE_INTEGER 了 )

The netizen added his own comments :

qinsi

Floating point numbers are often understood as decimals that can be used to represent integers , However, the format of floating-point numbers determines that the interval between adjacent floating-point numbers will increase with the increase of floating-point numbers . With float32 For example , As the exponent increases to near the mantissa bit Count , The interval between floating-point numbers is from 2^(-23), Gradually rise to 2^(-3)=1/8、1/4、1/2 and 2^0=1, If it continues to increase, the interval will continue to expand to 2^1=2、4、8,…, This starts skipping some integers . At this time, it is contrary to the recognition that floating point numbers are usually used to represent decimals .

As long as the programming language uses the floating-point number type provided by the hardware (IEEE 754), There will be such a phenomenon , It's not about the language .

The author has no reply ~

5. Net friend -jc9090kkk

type Myint int32 What are the advantages of this custom type in practical application ?

The author replied :

When using custom types , We are not considering the advantages and disadvantages , It is demand. .-- This sentence can be used in many places

With type Myint int32 For example , We do this , Obviously because of int32 Can't meet our needs . What needs cannot be met ? The first is abstraction , We need to build higher-level abstractions ; The second is that we can't afford to go Primitive types int32 Add the methods we want , Only through custom types .

Other netizens -tequ1lAneio

Hello Teacher , In which scenarios will type aliases be used ?

The author replied : Type aliases are added go The original intention of is to refactor , This is also the main scene . In the 17 It will also be mentioned in the lecture .

Net friend -Howe

teacher , What are the application scenarios for custom types and type aliases ? For example, customize a type , In essence int32, Then why not use it directly int32, It looks like a little grammar sugar , Not very useful , In particular, type aliases

The author replied :

Native int32 There can't be a way , But custom types can have methods .

For example, I define a named Age The type of :

type Age int32.Age It can be used as “ Age ” The abstraction of . We can Age Define methods .

As for type aliases , More for refactoring code or secondary encapsulation based on existing packages .

6. Net friend - Vfeelit

Many languages do not have unsigned integers Whether unsigned integers are necessary ?

in addition , No unsigned floating-point numbers , Is it unnecessary

The author replied :

1. Daily coding , Unsigned integers are used much less frequently than signed integers , And the problem of unsigned number overflow is difficult to detect .

The only advantage of unsigned is that its maximum representation range is larger than that of signed integers .
2. In terms of the representation principle of floating-point types, it does not seem necessary .

The above question is a bit convoluted , Personal brevity

problem 1:  Can we not use unsigned integers ?-- Use less , But it still needs to be .

problem 2:  Can you not use unsigned floating-point numbers ?-- From the representation principle of floating point type , Sure .

7. Net friend -Niverkk

In the text Go use 2 Complement (Two’s Complement) Bit coding method as an integer
d1 := 0b10000001
fmt.Println(int8(d1)) //-127
fmt.Printf("%b\n", int8(-127)) // -1111111
But is the format literal still in the original code ?

The author replied : It seems to be . May be go The team believes that the results of this output are easier for humans to read :).

8. Net friend - I'm Baolong 、

type Myint int
type MyMapp map[string]int
func main(){
var x Myint
var y int
x=y// Will report a mistake
mp1:=make(MyMapp)
mp2:=make(map[string]int)
mp1=mp2 // No mistake.
}
Why did the teacher map You can't report an error

The author replied :

int And map[string]int Although it's all go Primitive types , But they are different .int stay go Is classified as defined type A class , and map[string]int It is not defined type.

So two defined type: int And MyInt Mutual assignments must be explicitly transformed . and map[string]int And MyMapp in , The former is not defined type,go The language is regulated : In this case , You can assign values directly . Refer to here for details :

The Go Programming Language Specification - The Go Programming Language

------------------------------------------------------------ Separator ------------------------------------------------------------

13| Basic data type : Why? Go To natively support string types ?- Geek time

Exercises after class

Go Provides a variety of string connection services , Including based on +/+= Character connection of 、 be based on strings.Builder、strings.Join、fmt.Sprintf And other functions to connect strings . that , Which connection mode has the highest performance ?

Net friend - Sword clasping scholar

Connect 5 m helloworld
2.6157056s + Splicing method
994µs strings.Join()
8.9755ms string.Builder

The author replied :

1. Vfeelit

rune yes int32 Alias Unicode Coding is not negative Why not uint32 Another name for ?

The author replied :

Good question . I have also thought about this question , There is no official answer . But from the point of view given by the community , There are two main considerations :1.int32 It's enough to show unicode All code points 2. int32 Can be negative , Easy to detect overflow (overflow) Or anything else based on int32 The calculation is wrong .

2.  How are you? , friend .

It can be understood as []rune Deposit is Unicode Code point or UTF-32 code , and []byte and string Deposit is UTF-8 code

The author replied : One rune Store a unicode Code point or utf-32 Four byte encoding of ; From a byte perspective ,string The corresponding underlying storage is utf8 code .

3. lesserror

Tony Bai The teacher's article is about Go The explanation of string types is very detailed .

But there are still the following puzzles , Please ask the teacher to see and answer :

1. How to understand :“ Face value ” It's more appropriate ?


2. unsafe.Pointer This usage , This is very common in the source code , Will this column explain ?

3. var s string = " Chinese ", Variable declarations like this , The best practice is to delete string Type declaration of ? The editor on my side directly prompts me that I am redundant .

4. About string Data of type is immutable , The resulting benefits , I feel I can talk about it in depth , The feeling here is still quite abstract .

The author replied :

1. Face value (literal) Is a fixed value in the source code , It is written directly in the source code , immutable , Without any calculation, we can literally see that “ value ”. In programming language > In speech , Usually a literal can be roughly inferred from its literal type . In addition, literals can be used to initialize variables , It can also be used as the value of a constant .

2. unsafe The package is an advanced topic , As an introductory column, this column will not go too far .
3. Um. , use s:=" Chinese ", It is estimated that the editor will not prompt
4. Good suggestion !

4. qinsi

So here comes the question ,raw string How to use backquotes in ?

The author replied : Backquotes are the only “ a fish escaped through the seine ”:).

5. Bynow

& and unsafe.Pointer What's the difference? ?

The author replied : With a:=1; var p = &a For example ,& Is the address operator .unsafe.Pointer yes go Common pointer types in languages , Any pointer can be converted to unsafe.Pointer type , conversely unsafe.Pointer You can also switch back to any pointer type . Example :

i := 11
var p = unsafe.Pointer(&i) // int The pointer -> unsafe.Pointer
pi := (*int)(p) // unsafe.Pointer -> int The pointer

6.  Multiple parameters

teacher , About utf-8 Do not consider the problem of byte order . Can you understand ,utf-8 A character of is composed of 3 Bytes are encoded and compared byte by byte , For example, the value encoded by the first byte is between these values , It must be single byte encoding , The second byte encodes a value between , That must be double byte encoding , and utf-32 need 4 Bytes together ? that , once 4 If the bytes are considered together , It is necessary to involve this 4 Is a byte a large endian or a small endian ?

The author replied : Right .

I'm Baolong 、

Hello, teacher , A Chinese character stay utf-8 The encoding is followed by three bytes , Why is there no byte order problem , I'm a little confused

The author replied : utf8 It's variable-length code , The encoding unit is a single byte , There is no one at the top 、 The question of who is in the low position . and utf-16 The encoding unit of is double byte ,utf-32 The coding unit is 4 byte , We need to consider the byte order problem .

7.  Sheep and sheep

var s string = "hello"
s[0] = 'k'
s = "gopher"
According to the following content, we know s[0] Is string s The first byte of , Not the first character , Is it not possible to put characters k Directly assign to s[0] Well ?go Is the string of , Out-of-service index To get a single character ?

The author replied :

s[0] = 'k' This can't be .go string It's immutable .
go The string subscript operation can only get the first byte , Not the first character .

8.  light

What is the difference between these two ways of writing .

valid := []byte("Hello, The world ")
invalid := []byte{0xff, 0xfe, 0xfd}

fmt.Println(valid)
fmt.Println(invalid)
fmt.Println(utf8.Valid(valid))
fmt.Println(utf8.Valid(invalid))

The author replied :

valid Is to make a legal unicode String conversion to utf8 code ( adopt string-> The transformation of slices ). Therefore, the converted byte sequence is also a legal utf8 code .invalid Three bytes in a slice do not constitute a legal unicode Character utf8 code , therefore invalid.

If you use the following code
      valid1 := []byte{231, 149, 140} // unicode character “ world ” Of utf8 code
be Valid Will be output true
fmt.Println(utf8.Valid(valid1)) // true

9. Elvis Lee

string It's a 8 A collection of bits and bytes , Usually but not necessarily UTF-8 Encoded text .string Can be null , But not for nil.string The value of is unchangeable .
string The type cannot be changed , But it can be replaced , because stringStruct Medium str The pointer can be changed , It's just that the content of the pointer can't be changed , That is to say, every change string , You need to reallocate memory once , The space previously allocated will be gc Recycling .

The author replied :

10.  Multiple parameters

The teacher told me that coding is the clearest thing I have ever seen . There's a little problem , Namely Go Medium string What is stored in memory should still be UTF-8 Encoded data ? and rune The way we use it Go The source code is implicitly converted ?

The author replied : you 're right ,string What is stored in memory is utf8 Encoded bytes . image for range The result of this cycle rune, yes Go Compiler replacement at compile time .

11.  Evolutionary bacteria

String is a very common thing , I can't help thinking ,go There should also be the problem of garbled strings ?

The author replied : To be honest , This has been for many years , I haven't met . Unless your environment is not using utf8 Encoding mode .

12.  Sheep and sheep

Second point : There is no end ’\0’, And the time complexity of obtaining the length is constant , Eliminates the overhead of getting string length . The time complexity of getting the length of string bytes is O(1) Well ? If you use utf8 Library function utf8.RuneCountInString() Gets the character length of the string , I don't know the time complexity

The author replied :

1. The time complexity of getting the length of string bytes is O(1) Well ? - Yes
2. Use utf8 Library function utf8.RuneCountInString() The time complexity of getting the character length of a string should be o(n).

13.  Roger

About splice performance , Is there any authoritative article about , I compared the results of the test fmt.Sprintf Basically the worst

The author replied : There is no authoritative article , Write it yourself benchmark You can generally judge that the performance is better after running .

------------------------------------------------------------ Separator ------------------------------------------------------------

------------------------------------------------------------ Separator ------------------------------------------------------------

------------------------------------------------------------ Separator ------------------------------------------------------------

------------------------------------------------------------ Separator ------------------------------------------------------------

Subsequent complement

...

3. problem / Add

TBD

4. Reference resources

12| Basic data type :Go What are the natively supported numeric types ?- Geek time

13| Basic data type : Why? Go To natively support string types ?- Geek time

Subsequent complement

...

原网站

版权声明
本文为[A boy in plain white]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203021356019985.html