Talk less , Let's start with the last piece of code , Guess the expected effect .

package main
import (
"fmt"
) type student struct {
Name string
Age int
} func main() {
m := make(map[string]*student)
stus := []student{
{Name: "zhou", Age: 24},
{Name: "li", Age: 23},
{Name: "wang", Age: 22},
}
for _, stu := range stus {
m[stu.Name] = &stu
} fmt.Printf("%+v\n", m) for k, v := range m {
fmt.Printf("k:%s v:%v\n", k, v)
}
}

out:

 map[zhou:0x42114e100 li:0x42114e100 wang:0x42114e100]
k:li v:&{wang 22}
k:wang v:&{wang 22}
k:zhou v:&{wang 22}

Isn't it amazing , Why is the result not expected ,map The values of are all one ?

reason :for range Every time it happens k , v It's all a copy of a value , No stus It's worth quoting , So that's what happens .

Detail analysis :

 for _, stu := range stus {
m[stu.Name] = &stu
} // stu Is in for A local variable applied in , The address is :0x42114e100, Every copy stus Corresponding value in .
// After iterating through ,stu Every time it's reassigned , and map The record is Variable stu Corresponding address value , Therefore, it will not produce the expected effect .

Quick solutions :

 for _, stu := range stus {
a := stu
m[stu.Name] = &a
}

For the record .

Golang -- range More related articles in Xiaokeng's mind

  1. go The variable of redeclare The problem of ,golang A small hole in the

    go There are several ways to declare variables in : 1 By keyword var Make a statement for example :var i int   And then the assignment operation i = 5 2 The simplest , By means of symbols := Make declarations and assignments for example : i:=5 golang Meeting ...

  2. Golang The pit prevention tips of

    Golang The pit prevention tips of author : Yin Zhengjie Copyright notice : Original works , Declined reprint ! Otherwise, the legal liability will be investigated . As a little white , I didn't get in touch with programming partners before , It's hard to avoid stepping into some pits , For example, when you first get started, you need to install the environment , Study Gol ...

  3. Golang Pit two in the middle

    Golang Pit two in the middle for ...range For the last two weeks Golang Do the project , To write web service , I wrote about 5000 lines of code in two weeks ( Business code plus unit test case code ). use Go It's a great feeling , High coding efficiency , Good operation efficiency , use ...

  4. mciSendString The two small pits of

    Just fixed the code of your own small alarm clock . pit 1:REPEAT The scope of the options It's used well , Then choose .wav file , There's no sound …… EH ,MCI Definitely support .wav ah …… Think carefully , I used to choose . ...

  5. Be careful Android in TextView Control of a small hole , use android:theme To dynamically load when setting styles layout The style will be lost

    Be careful Android in TextView Control of a small hole , use android:theme To dynamically load when setting styles layout The style will be lost The pit , We must pay attention to it , For example, in use ListView When , If in List_ ...

  6. C# Medium Infinity There's a little pit

    ( This article is also published in my official account of WeChat "dotNET Daily essays ", Welcome to the QR code on the right .) Something happened at home yesterday , It's not convenient to surf the Internet , There is no push article . I am tired today , It's not going to be long . Let's give you a brief introduction to ...

  7. Use EMMET A small hole in the middle

    Use EMMET Write HTML When , It's a great thing . But when I use it today , Found a small hole . I didn't notice it before , But it needs to be very careful . form[action="/process" metho ...

  8. About CSS3 in transform The pit of transformation

    2017 year 6 month 30 Japan 15:05:46 Today I'm writing a demo When , Find out CSS3 in transform A property of transformation . First , Let me first describe what I found ( Problem reproduction ): <div class=" ...

  9. Vue Application in CORS Realization AJAX Cross domain , And where it is form data and request payload Small pit treatment

    The basic concept part ( One ): understand CORS Say Vue The cross-domain AJAX, I want to sort it out first CORS Cross domain ," Cross-domain resource sharing "(Cross-origin resource sharing), It's a W3 ...

Random recommendation

  1. mysql-Federated storage , remote table , amount to sql server Of linked server

    MySQL Different storage engines are provided for different functional requirements . The so-called storage engine is MySQL The specific implementation of specific interface . FEDERATED It's one of the implementations for remote databases . In general, creating a table in a local database will be done in the database directory ...

  2. Let's work with snailren learn java-(13) character string

    “ I haven't written this series for a long time . In fact, some people are watching , But I don't think it's interesting to write some basic ones . Now the plan is to read the whole book , Finally, it's integrated into one blog, Screen out some things that you don't notice or have a deeper understanding ” In writing programs , character string Strin ...

  3. BZOJ1012 [JSOI2008] The maximum number maxnumber

    The copyright of this article belongs to ljh2000 And blog park , Welcome to reprint , But keep this statement , And give a link to the original , Thank You for Your Cooperation . The author of this article :ljh2000 The author blog :http://www.cnblogs.com/ljh2000-jump/ ...

  4. zookeeper kazoo Basic Usage

    http://kazoo.readthedocs.org/en/latest/basic_usage.html Basic Usage Connection Handling To begin usi ...

  5. Android_Studio And SDK download

    Android Studio includes all the tools you need to build apps for Android. DOWNLOAD ANDROID STUDIO 2. ...

  6. php Get address bar parameters

    javascript Realization : top.location.href The address of the top level window this.location.href The address of the current window PHP Realization : // Get domain name or host address echo $_SERVER[' ...

  7. 【codevs2205】 A sequence of equal differences

    The main idea of the topic : Given a length of N Sequence , Find the number of arithmetic sequences in this sequence . Answer key : According to the meaning of the title, it should be a sequence count dp. set up \(dp[i][j]\) Says to the first i End of item , The tolerance is j The number of arithmetic sequence of , Then state transition ...

  8. [LeetCode] 102. Binary Tree Level Order Traversal_Medium tag: BFS

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...

  9. 【C# Little knowledge 】C# Summary of some confusing concepts in ( 3、 ... and )--------- structure ,GC, Static members , Static class

    Catalog : [C# Little knowledge ]C# Summary of some confusing concepts in [C# Little knowledge ]C# Summary of some confusing concepts in ( Two ) --------------------------------------- Split line ----------- ...

  10. 【c】 The linear table

    Data object set : The linear table is N(>=0) An ordered sequence of elements ,a1,a2,a3.....a(N-1),aN,a(N+1) The basic operations on a linear table are : ⑴ Linear table initialization :Init_List(L) Initial conditions : surface L ...