Golang initialize pointer to struct. " – Dec 11, 2017 · Here's a way to use atomic.


Golang initialize pointer to struct May 11, 2021 · I was wondering how to initialize a nil pointer to a struct, when the initialize function receives this argument as interface{}. Mar 9, 2017 · It returns a reflect. Reason: In the case of embedded values, when initializing the external structure, a whole block of continuous memory will be applied, which can also initialize the internal structure. In this context reflect. Age is 0 You should explain that passing the pointer to the interface directly works because if MyStruct conforms to a protocol, then *MyStruct also conforms to the protocol (since a type's method set is included in its pointer type's method set). LoadPointer (based on your example):. My question is if that is possible and if, how! See the code below (with link to Go playground): May 8, 2014 · The first returns a copy of the struct, the second a pointer to the struct value created within the function, the third expects an existing struct to be passed in and overrides the value. Jun 22, 2014 · The issue is that I do not know how to obtain the address of a non-pointer field. To define a new struct type, you list the names and types of each field. Buffer doesn't get you a nil pointer, it gets you a bytes. Pointer and unsafe. Supposing you have a struct like this : type Thing struct { Name string Num int } then, if the zero values aren't fitting, you would typically construct an instance with a Dec 3, 2019 · An easy way is to use reflection to iterate over the fields of the struct, obtain their address (pointer), and use fmt. I use this rather extensively and it works well. A slice is a reference type. Feb 11, 2015 · When you initialize the struct, Use Pointer to your struct. When it comes to structs a common reason for using pointers is that pointers can have nil values, where primitives can't. e1 := Event{Id: 1, Name: "event 1"} is initializing the variable e1 as a value with type Event. Nov 21, 2015 · Function to nil a pointer; using unsafe. 00 PM"} But it shows a runtime error: panic: runtime error: invalid memory address or nil pointer dereference Jun 13, 2018 · Another option to make a pointer point to something "useful" is to assign the address of a variable to the pointer variable, like this: value := 12345 // will be of type int guess := &value But this solution modifies the pointer value, not the pointed value. Pointer Jun 16, 2021 · Because the map keys have two possible values, true and false, you might be able to simplify the code by using a struct instead of a map: type Register struct { t, f []bool } register := Register{t: make([]bool, len(arr))} The struct fields in register are addressable, so you can use &register. How do I initialize a pointer to pointer in golang? 0. Println("Test is Oct 21, 2011 · In order to do that you need reflect. New(reflect. StorePointer and atomic. Modifying External Data: When you need to modify a variable defined outside the current scope. N) // pointer to struct - addressable ps := reflect. NewAt is different than reflect. Golang provides multiple ways to assign values to struct fields: 1. In Go, a struct is defined using the type keyword followed by the struct name and the struct Pointer to a Struct. An edit: I guess I used the wrong word and should have said allocate. To accept a pointer to any type, we can use unsafe. func main() { // Initializing a Person struct without field names alice := Person{"Alice", 30} fmt. The second . To easily tell if a time. 8. Per the sync package docs: "Values containing the types defined in this package should not be copied. unsafe. Especially because it's simpler to understand, autocomplete and unit test. Thanks. " – Dec 11, 2017 · Here's a way to use atomic. The term const has a different meaning in Go, as it does in C. Aug 20, 2019 · An application can create a struct programmatically using reflect. May 24, 2015 · How can to initialize any fields in golang types? For example: type MyType struct { Field string = "default" } you can return a non-pointer type. So you need to initialize it: var person *Person person = &Person{} // Sets the pointer to point to an empty Person{} struct Or in a single statement: If you're using Go version 1. org Dec 21, 2010 · Good catch by deamon. May 30, 2022 · I have a generic func func foo[T bar]() which I need to pass a type which is a pointer to a struct foo[*zab](). To declare a null pointer in Go, you can use the nil keyword. I've seen all of these patterns be used in various contexts, I'm wondering what the best practices are regarding these. New works kind of like the built-in function new // We'll get a reflected pointer to a new int value intPtr := reflect. Sizeof(data[0]) for i := 0; i < size; i++ { data[i] = *(*byte)(unsafe. Sep 17, 2017 · I have initialized a struct : type DayAndTime struct { days string time string } I have initialized an empty set of array of this DayAndTime type: day := []DayAndTime{} And put a value in it: day[0] = DayAndTime{"Monday", "8. To do a simple service locator Code is like this package main import ( "fmt" Feb 28, 2014 · Going off of what @Volker said, it's generally preferable to use &A{} for pointers (and this doesn't necessarily have to be zero values: if I have a struct with a single integer in it, I could do &A{1} to initialize the field). Overall there is no need to use pointer to a slice rather than plain slice in your case, because you don't use append, to there is no chance for reallocation of backed storage. Value. The zero value of a struct value is not nil. Using the `array literal` syntax Aug 24, 2018 · Go basic types have defined zero values and cannot be nil. Pointer is a language support, it's a special pointer type which can be converted from and to any pointer type. The spec says the zero value is "false for booleans, 0 for integers, 0. You can have a setDefaults() method on your settings struct that gets called in the constructor for any unset field. Sscan() to scan the string value into the field. Println(b Dec 13, 2016 · I have the following data structure. Same goes for Name. IsZero() . You might want to do this so you’re not copying the entire struct every time you append to the slice. You can take the address of a struct value of VHE1, convert it to Pointer, and convert the result Pointer to a pointer to the target data type. Pointers store the memory address of the struct, allowing multiple variables or functions to refer to and modify the same underlying data without May 6, 2017 · I'm trying to assign a value to a struct member that is a pointer, but it gives "panic: runtime error: invalid memory address or nil pointer dereference" at runtime package main import ( "fmt" "strconv" ) // Test type stctTest struct { blTest *bool } func main() { var strctTest stctTest *strctTest. Dereference the pointer and now you already have Feb 13, 2016 · the normal way to initial a struct with anonymous member is like this: package main import "fmt" type AA struct { int xx string } func main() { a := &amp;AA{ May 2, 2013 · Serialization is likely the proper answer. It returns a pointer to the newly created struct. Feb 26, 2020 · This is a very important property of using pointers as arguments. type mystruct struct { Name string Power int } My purpose is to write a function that takes as input a slice of type *mystuct and returns a slice of type int containing the "Power" property taken from the input slice. The question gets the struct as a value, but it's likely that a pointer to the struct is more useful to the application. Println(n. string) } When an anonymous field is a struct and has fields of its own, those fields are promoted to be accessible as if they were direct fields of the parent struct (unless the parent struct already has a field with that name): Apr 11, 2023 · Pointers to a struct. Here is an example: type Z struct { Id int } type V struct { Id int F Z } type T struct { Id int F V } The above code represents my test structures. 0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This is extremely useful since we want to change the original rather than a copy of it. func Pointer[T any](d T) *T { return &d } How to use: type Example struct { isActive *bool } ex := Example { isActive: Pointer(true), } Jan 29, 2020 · We use pointers to share data, but that doesn't always mean it is more memory efficient or more performant. Jan 18, 2015 · type myType struct { string } func main() { obj := myType{"Hello World"} fmt. You can access individual fields with dot notation. Do I first initialize the strings and then the structure. 2 ways to create and initialize a new struct. Let’s see what these look like for a simple struct named Person : package people type Person struct { age int name string } // struct literal person := & Person{ age: 25 , name: "Anton" , } // new build-in person := new (Person) // person Aug 29, 2014 · The receiver is passed by value, including the pointer receiver: it is a copy, and changing its value doesn't change the initial pointer receiver on which the method is called. Direct Initialization type Employee struct { Name string Salary float64 Active bool } func main() { // Complete initialization emp1 := Employee{ Name: "John Doe", Salary: 5000. " Field Value Assignment Basic Assignment Methods. Struct { // exported field f := s. com Nov 1, 2024 · The variable p1 is an instance of this struct. UnsafeAddr()) as that pointer. how to create a pointer to reflect. 50, Active: true, } // Partial initialization emp2 := Employee{ Name: "Jane Smith", } } It's very common for code (especially code fully under your control) to assume you initialize the data structure correctly. Type(), using unsafe. If you don't want to go with separate struct definition for nested struct and you don't like second method suggested by @OneOfOne you can use this third method: Feb 15, 2018 · How do I initialize a struct with a double pointer field? I am trying to initialize a struct as below: type atype struct { val string } a := &amp;struct { StringValue string Pointer ** Aug 28, 2019 · The first method. Given the above, this answer shows how to do the following without defining the type at compile time: Zero Values and Empty Structs. Request in the following function: Oct 15, 2016 · I m trying to assign a pointer to a struct to the value of an already initialized struct pointer of the same type. Elem() if s. If you want to print the pointed value, dereference the pointer and pass the pointed value, e. with using the builtin new(): p = new(int) You assign to the pointed value: *p = 3 fmt. That means it's essentially a hidden struct (called the slice header) with underlying pointer to an array that is allocated dynamically for you. Depending on how often you need to pass around the Vertex struct, it might or might not be more efficient to pass a pointer to it. See "Why are receivers pass by value in Go?". Safety Be cautious when working with Jun 1, 2021 · It's the same as using an int value or an *int pointer. Using pointers is nanoseconds faster, but the real reason is developer ergonomics! It’s cumbersome to make changes to an array of structs. Categories = new([]Category) Mar 31, 2013 · This pattern is widely used in golang, but I believe this is not useful for initializing structs embedded in other structs, only for creating new pointers to them. I come up with the following code: data := make([]byte, size) stepSize := unsafe. Sscan() will handle the different types of fields for you. A function Setup returning a new *Foo would work better: play. Also please note that since your structs contain pointers, when copying a struct, pointer values will be copied and not pointed values. Example: Jan 4, 2024 · Discover the ins and outs of Golang arrays and structs with this comprehensive guide. It is typically compared with classes in object-oriented programming language and is termed as a light-weighted class that supports composition Aug 30, 2021 · type StringSet struct { m map[string]struct{} mu sync. Pointer(p)) p += stepSize } fmt. You need to make sure that the address pointed by the pointer is big enough to hold the structure contents. (int) // Prints 0 fmt. If you need a struct with optionals field, you'd use pointers Aug 11, 2017 · The {1, 2} seems to be a structure called "anonymous struct", but it confuses me since it works fine even when I am trying to fill in *Ex pointers instead of Ex struct. Name is "", emptyPerson. As a result, it will be possible to modify/access the map concurrently without locking. Interface(). Println(p) // prints &{"Alice" 30} I want to point your attention to the output &{Alice 30}. Here is an example: var ptr *int = nil Jul 19, 2017 · For example for a struct with four properties, if your embedded struct is one of the first fields then you'll need to initialize it like ErrorValue{nil, NamedValue{"fine", 33}, nil, nil} which doesn't look as clean as passing the unqualified type name of the embedded struct in. First off, you can't initialize arrays and slices as const. Actually this is your case. Calling a method on a receiver assumes that the receiver is already initialized. Yes, since *Node implements Nexter, your p variable may hold a value of type *Node, but it may hold other types as well which implement Nexter; or it may hold nothing at all (nil value). Sep 20, 2015 · I'm new to developing in Go. Jul 12, 2017 · package main import ( "fmt" "reflect" ) func main() { type t struct { N int } var n = t{42} // N at start fmt. Buffer object with all its fields initialized with their zero values (in machine terms, with zero bytes). But if you pass the mutex itself, or pass a struct containing a mutex (not a pointer to the struct) you'll create a copy. g. Using the new function, which returns a pointer to a newly allocated struct. Furthermore, when I try the following code, it complains syntax error: Jul 25, 2013 · I have the following struct which contains a net/http. Fields are initialized in the order they are defined in the struct. Benefits of using a Pointer to a Struct. A pointer is a data type that stores a memory For embedded structs, if the embedded one is a value, it can be initialized; if the embedded one is a pointer, it cannot be initialized. with using the builtin new(): book. Aug 14, 2018 · You're defining a struct to have 3 fields: Year of type int, this is a simple value that is part of the struct. Println(*pointer) // Or, if we dereference: 0 } The syntax is only slightly different, but all of the principles we have already discussed are the same. Oct 18, 2013 · The method sets of these two values, the Vertex struct and the *Vertex pointer, may be different. New, which would return a pointer to a freshly initialized value. May 22, 2017 · Let's say I have a struct with another struct embedded in it. But if you consent to unsafety and actually need to read struct as bytes, then relying on byte array memory representation might be a bit better than relying on byte slice internal structure. The first method as mentioned is a bit better but I can't help but Oct 2, 2014 · It looks like you are trying to use (almost) straight up C code here. The Type field, however, is a slice. And in general you need to initialize pointer types before using. We want to change the value of a variable of pointer type. Jan 29, 2022 · Out-of-the-box Go gives us 2 ways to initialize structs - struct literals and the new build-in function. Nov 26, 2024 · Intermediate Struct Initialization without Field Names. Dec 31, 2018 · In Go when I have an array, or slice, of structs, I prefer to always make that an array of pointers to the structs. The new keyword can be used to create a new struct. Time is its zero value, you may use Time. Using the `make` function 2. To create a pointer to a struct, you can simply use the address-of operator & before initializing its values. : var p = new(int) *p = 12 fmt. There are multiple ways to initialize a struct in Go: Initialization as a value: foo:=Foo{}, you can also create it in the default way var foo Foo; Initialization as a pointer: foo:=New(Foo), of course, you can also initialize as a value first and then take the address foo:=&Foo{} Aug 31, 2021 · Note that in other cases it may not be necessary to automatically turn to pointer: you may use the zero value of time. Explore practical examples and real-world use-cases to elevate your coding skills. Kind() == reflect. Pointer. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. Pointer receivers can mutate their receiver through the pointer - passing in memory wouldn't work. The struct keyword in golang, also known as structure, is a user-defined data type that allows us to combine or group items of different types into a single type. If i declare a slice of struct values eq: mySlice := make([]UselessStruct, 5) then this creates 5 empty structs - appending doesn't replace the empty structs, but rather keeps on adding to the slice, so the end result with this code: Dec 7, 2015 · How to initialize struct pointer via reflection. println(data) Jun 20, 2024 · Defining and Initializing Golang Structs Defining. Promoted fields cannot be used as field names in composite literals of the struct: co := Container { Base : Base { b : 10 }, c : "foo" } fmt . FieldByName("N") if f. Besides being a stylistic concern, the big reason that people normally prefer this syntax is that, unlike new, it Passing in a settings struct with pointer fields is also nice instead of functional options. Now here is the actual function which traverses a specified structure and lists details about it: May 11, 2015 · This is because a variable of static type Nexter (which is just an interface) may hold values of many different dynamic types. type Base struct { ID string } type Child struct { Base a int b int } When I go to initialize Child, I can't initialize the ID field directly. Aug 15, 2020 · When using a struct literal, however, we have to initialize the embedded struct as a whole, not its fields. . Println(obj. Mar 3, 2017 · I have a struct that I want to initialize with a slice of structs in golang, but I'm trying to figure out if there is a more efficient version of appending every newly generated struct to the slice: Feb 26, 2023 · Null pointers are often used to indicate that a pointer is not initialized or has been deallocated. It seems like, though you're able to initialize a dictionary, structure, etc. It might be because the curly bracket syntax seem to lend itself exclusively to [composite?] types. IsValid() { // A Value can be changed only if it is Jan 24, 2016 · There are couple of issues with the code: Map needs to be initialized using make function. 1. t to get the *[]bool. g := &Graph{ connections: make(map[Vertex][]Vertex), } Sep 30, 2014 · There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization. In this case, the interface is the empty interface, so it accepts all types anyway, but still. Mue was possibly thinking of the more common pattern of including the lock as a value rather than a pointer. What happens is that, instead of changing it locally, the pointer changes it at the original value. Elem(). How can I make this code work assuming that I will always be sending a pointer, and the type of the argument of the function is strictly interface{}? Jun 9, 2015 · The Go Language Specification (Address operators) does not allow to take the address of a numeric constant (not of an untyped nor of a typed constant). e2 := &Event{Id: 1, Name: "event1"} is initializing e2 as a pointer to a value of type Event As you stated in the comments, the set of methods defined on a value of a given type are a subset of the set of methods defined on a pointer to a value of that type. Use Cases for Pointers Efficiency: Instead of copying large structs or objects, you can pass a pointer. Println(*p) The same goes with pointer slices: you first have to initialize it, e. Go is extremely good and fast at copying data. Time (which is a struct) to indicate the "missing time" state. package main import ( "fmt" "sync/atomic" "unsafe" ) var addr unsafe. Let’s see what these look like for a simple struct named Person : package people type Person struct { age int name string } // struct literal person := & Person{ age: 25 , name: "Anton" , } // new build-in person := new (Person) // person Sep 14, 2019 · For an operand x of type T, the address operation &x generates a pointer of type *T to x. For example, How would I use your NewConsole() to initialize Console1 and Console2 inside ConsolePair defined like this? <code> type ConsolePair struct { Console1, Console2 Console Sep 13, 2021 · package main import ( "fmt" ) func main() { pointer := new(int) // This will initialize the int to its zero value of 0 fmt. I need to initialize it without using nested initialization. TypeOf(a)) // Just to prove it b := intPtr. I'm not sure why you need pointers here, would be best to just declare all fields to be non-pointers. Go makes it easy however to copy an entire struct with a simple assignment, so we may think that passing arguments by value is all that is needed to have immutability at the cost of copying. Return value from map is non-addressable, this because if map is growing it needs to relocated which will cause memory address to change. Go has a few differences. var p *int You have to initialize it first, e. The express *Pointer means "the object that Pointer points to". The default zero value of a struct has all its fields zeroed. Also note that embedding is not really a requirement, it just makes your types and their usage more smooth. Go also supports initializing a struct without specifying field names. golang. Since the zero value of a Mutex is a ready-to-use unlocked Mutex, it requires no initialization and including one as a value is common. blTest = false fmt. 0 for floats, "" for strings, and nil for pointers, functions, interfaces Aug 25, 2016 · The expression *Type means "pointer to Type". Pointer(field. You can also create a pointer to a struct as shown in the below example: Oct 22, 2013 · With a type: type A struct { B int, C *int } How do I initialise a pointer member to a non-zero value inline, without creating temporaries? a := A{ B: 42, C: ?, } By the end of this article, you will have a solid understanding of how to initialize an array of structs in Golang. There are three ways to initialize an array of structs in Golang: 1. ValueOf(&n) // struct s := ps. Jun 6, 2020 · In order to resolve this tension, I've attempted to create a top-level "container" struct that holds a reference to the dependent struct and interface, and then with a method on the container struct, assign as a member of each component struct that top level container's pointer to the other struct. When a struct is declared without initialization, it gets zero values for its fields: var emptyPerson Person // emptyPerson. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. RWMutex } any accidental or intentional assignment/copy of a struct value will create a new mutex, but the underlying map m will be the same (because maps are essentially pointers). package main import ( "fmt" "reflect" ) func main() { // one way is to have a value of the type you want already a := 1 // reflect. Aug 28, 2023 · 7. Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. There are two common ways to create a pointer to a struct in Go: Using the & operator to get the memory address of an existing struct. Value representing a pointer to a value of the specified field. type GeneratePlan struct{ Mod Oct 1, 2019 · I have the following structure in Golang . p1 := passport{} var p2 passport p3 := passport{ Jul 29, 2012 · You need to allocate memory to the pointer so that you can do anything meaningful with it. If you pass a Vertex struct to a function, the function gets a copy and your Vertex struct will never be modified. Nov 7, 2021 · If you pass a pointer to a function, the function can mutate the data at that address. Finally, if you Jul 6, 2019 · that's another problem - you have type "pointer to a slice of car", not "a slice of car". 18 or later, you can take advantage of the newly introduced generics feature to create a utility function that generates a pointer to any given type. Data Structures: Pointers are essential for building many data structures, like linked lists or trees. Pointer can be cast to any pointer type, so this is your "gateway" between different pointer types. Println(pointer) // Aha! It's a pointer to: 0xc000018030 fmt. fmt. with a value (using curly-brackets), the same syntax can not be used to initialize an integer (all scalars?) pointer with a value. Jan 24, 2016 · There are couple of issues with the code: Map needs to be initialized using make function. Jun 10, 2011 · How do I initialize a pointer to a structure of type above as well as initialize the pointer to the 10 strings (incall[]) inside the structure. 0. Mar 17, 2017 · One would expect person to be initialized (zeroed) after calling . In func foo I want to initialize the value using one of new() or var t T. Jun 16, 2019 · When passing a struct to a function or assigning it to another variable, using a pointer to the struct instead of the struct itself eliminates the need to create a duplicate copy of the entire struct. my code is presented below: Jun 25, 2018 · You can read more about it in related question: Difference between golang pointers. That's a quintessential use of pointers, whether or not they're in a struct. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for integers, 0. StructOf, but all fields in the struct must be exported. // unknown field 'ID' in struct literal of type Child child := Child{ ID: id, a: a, b: b } Jul 5, 2018 · Now, I want to initialize a slice or an array with the known pointer, size and of course the data type. If you do not want a pointer behaviour, you can use null types from third party packages, Nov 22, 2017 · To make it more clear, once you've got a pointer to some instance of Stats and locked it, a pointer to this instance can be removed from the map, or the map entry which held it could be updated by another pointer — pointing to another instance of Stats, so once you're done with the instance, it might have become unreachable via the map. Declaring a Pointer to a Struct. Currently they are nil. Println(alice) } What i would like to do, is preallocate memory for 5 UselessStructs, stored as pointers. Request PathParams map[string]string } Now I want to initialize the anonymous inner struct http. Request: type MyRequest struct { http. Using the `new` function 3. e. If you want a value to be simply nillable, make it a pointer. Actually I am passing this structure as an argument to threads. Jun 18, 2015 · Any pointer can be cast to unsafe. – Mar 15, 2023 · Introduction to the Struct in Golang. Initializing an Array of Structs. type Person struct {Name string Age int} p := &Person{Name: "Alice", Age: 30} // creates a pointer to a Person struct fmt. The result is the same though in this simple example. Oct 17, 2015 · You don't need to name the fields in the data part, and you only need one string definition which can make it shorter if you want id := struct {name, ltype, value string}{name, ltype, value} Dec 4, 2017 · There is no way to define immutable structures in Go: struct fields are mutable and the const keyword doesn't apply to them. This data structure will be flushed to output a json file later. This is why you get an invalid indirect of worker literal if you try to use the expression *wrk, because you're saying "give me the object that wrk points to", but wrk isn't a pointer. Born() method which is a pointer receiver. Test if pointer to AWS Golang SDK struct is null/exits. Sep 24, 2014 · How do I declare an array of struct literal? Go: type Ping struct { Content []aContent } type aContent struct { Type string Id string Created_at int64 } func m Initializing structures that contain any type of pointer fields, including recursive struct fields; Preventing panics by ensuring that all fields of a struct are initialized; Initializing golang protobuf struct (the golang protobuf makes heavy use of pointers to embedded structs that contain pointers to embedded structs, ad infinitum) Aug 19, 2019 · เนื่องมาจากช่วงนี้ครบรอบหนึ่งปีที่ในทีมผมเคยทำ Golang project ที่เป็น Microservice เล็กๆ ใช้เวลาปั้นอย่างรวดเร็วร่วมๆ 3 Sprints — 1 เดือนครึ่ง แบบเริ่มจากศูนย์กัน package main import "fmt" type Employee struct {Id int Name string} func main {// You can also get a pointer to a struct using the built-in new() function // It allocates enough memory to fit a value of the given struct type, and returns a pointer to it pEmp := new (Employee) pEmp. Mar 22, 2015 · The crucial thing is var b bytes. Master the essentials and advanced topics like nested arrays and pointers to supercharge your Golang development. what data points to) is not copied. See full list on programiz. Jan 22, 2018 · I am starting to learn binary trees in cpp and dynamically allocated memories; thus to initialize a struct I do this struct node{ int val; node* left; node* right; }; //Initialize: node* Jan 10, 2019 · I am trying to literally initialize the following struct in GO: This is the struct: type tokenRequest struct { auth struct { identity struct { methods []string password struct { user struct { name string domain struct { id string } password string } } } } } Dec 31, 2015 · I was learning golang, and as I was going through the chapter that describes Structures, I came across different ways to initialize structures. A struct literal is usually used in this case. A pointer by itself just points to an random address. If you pass a copy of the value, it can only mutate its copy. Println(*p) // Prints 12 As to why to create a pointer to a value (and not a value), see these related questions: Aug 19, 2014 · struct { data *int // pointer to the data area len int cap int } When you pass a slice to a function, this structure is passed by value , while the underlying data area (i. Which is fine, because you're modifying one copy of the mutex (the one stored in the struct). 2. mombic xytf pjfit hoo tktqsllh pjnifh pphf uzefje igga hwkhsfo