Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the three common programming problems of Golang

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what are the three common programming problems in Golang". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the three common programming problems in Golang".

Question1: I need to maintain a set of "items". But, oh, no, Golang doesn't have a "Set" data structure.

One solution: Golang does not have "Set", but it does have "Map". The mapped keyset is a unique set of items.

You can do the following (https://play.golang.com/p/tayo3H5mi56):

Package main import "fmt" type Set struct {map [string] bool} func NewSet () Set {m: = make (map [string] bool) return Set {m: M} func (s * Set) Contains (val string) bool {_, ok: = s.m [val] return ok} func (s * Set) Add (val string) {s.m [val] = true} func (s * Set) Remove (val string) {delete (s.m) Val)} func main () {s: = NewSet () s.Add ("foo") fmt.Printf ("s has foo:% t. S has bar:% t\ n", s.Contains ("foo"), s.Contains ("bar") s.Remove ("foo") fmt.Printf ("s has foo:% t. S has bar:% t\ n", s.Contains ("foo"), s.Contains ("bar"))}

The advantage of using mapping as the underlying data structure of a collection is that you still benefit from ultra-fast mapping key lookup, basic hash optimization, and end up writing less code.

Question2: I need to compare two values, but "=" is not always valid.

One of the solutions: let's understand where "=" works and where it doesn't.

A structure that contains maps or slices

Type ABC struct {an int b string c [] int} Error: invalid operation: a = b (struct containing [] int cannot be compared)

A structure with a pointer.

Well, actually pointers are comparable, but they don't always give you the desired results.

A, b: = 1,1 fmt.Println (& a = = & b) / / False

Enter reflect.DeepEqual

Now, this will work on demand (in most cases):

/ ABC-A simple type type ABC struct {an int b string c [] int} var a = ABC {a: 1, b: "10", c: [] int {1,2}} var b = ABC {a: 1, b: "10", c: [] int {1,2}} reflect.DeepEqual (a, b) Example # 2a, b: = 1,1 fmt.Println (& a = = & b) / False fmt.Println (reflect.DeepEqual (& a) & b) / / True

It will give you better results-however, if you have floating point or time fields in your structure, you need to ignore them. You will need to write custom equals methods

/ ABC-A simple type type ABC struct {an int b string t time.Time / / Ignore time while comparing to structs} var a = ABC {a: 1, b: "10", t: time.Now ()} var b = ABC {a: 1, b: "10", t: time.Now ()} fmt.Println (a = = b, equals (a, b)) func equals (val1, val2 ABC) bool {return val1.a = = val2.a & val1.b = = val2.b}

Unless you have no choice, you won't want to write custom equals functions-but should you prefer reflect.DeepEqual to the = = operator? Essentially, if = = will be true, make sure that reflect.DeepEqual is true, and vice versa, not true. Therefore, reflect.DeepEqual can be used by default. Unless you have performance limitations, otherwise:

Func BenchmarkOperator (t * testing.B) {for I: = 0; I < t.N; iTunes + {if a = = b {}} func BenchmarkReflectDeep (t * testing.B) {for I: = 0; I < t.N If reflect.DeepEqual + {ns/op (a, b) {}} BenchmarkOperator-8 44614131 24.8 ns/op 0 B/op 0 allocs/op BenchmarkReflectDeep-8 823174 1558 ns/op 96 B/op 2 allocs/op

"=" is faster than reflect.DeepEqual. Faster.

Question # 3: I need to use a structure as a mapped key-but my structure contains slices, pointers, or fields to ignore.

One solution: the mapping key evaluation in Golang uses the = = operator instead of reflect.DeepEqual.

One way to solve this problem is to use custom key creation logic.

/ / Obvious solution that will not work type A struct {I * int} I, j: = 1,1a, b: = A {I: & j} m: = map [A] bool {} m [a] = true _, ok: = m [b] fmt.Println (ok) / / False key b doesn't exist in map m / / Custom keys- solution func customKey (a) int {return * a.I} I, j: = 1,1a B: = A {I: & I}, A {I: & j} m: = map [int] bool {} m [customKey (a)] = true _, ok: = m [customKey (b)] fmt.Println (ok) / / This will return true

Reward question: how do I compare two maps? [corollary of question 2 and question 3]

Https://play.golang.com/p/0ac2HIyiJ9g

Key, val: = "key", "val" key1, val1: = "key", "val" abc: = map [* string] string {& key: val} abc2: = map [* string] string {& key1: val1} def: = map [string] * string {key: & val} def2: = map [string] * string {key1: & val1} fmt.Println (reflect.DeepEqual (abc, abc2)) / / abc2 (abc2, abc2) / / false fmt.Println

The first thing to note is that you cannot compare maps through the = = operator. You can compare two maps through reflect.DeepEqual. According to the reflect.DeepEqual rule, the mapping key is compared to the = = operator, and the value is compared recursively to reflect.DeepEqual.

Thank you for your reading, the above is the content of "what are the three common programming problems of Golang". After the study of this article, I believe you have a deeper understanding of what the three common programming problems of Golang are, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report