What is difference between these functions? [closed] - go

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
What difference between the following functions?
func DoSomething(a *A){
b = a
}
func DoSomething(a A){
b = &a
}

First function receives pointer to value of type A. Second receives copy of value of type A. Here's how you call first function:
a := A{...}
DoSomething(&a)
In this case DoSomething receives pointer to original object and can modify it.
And here's call for second function:
a := A{...}
DoSomething(a)
In this case DoSomething receives copy of a, so it can't modify original object(but if original object contains pointers to other structs it can modify them)

func DoSomething(a *A) { // a is a pointer to given argument of type A
b = a // b is a copy of a, which is also the same pointer
// this is useful to change the given object directly
}
func DoSomething(a A) { // a is a copy of the given object type A
b = &a // b is the pointer of a
}
Remember, a pointer is a variable which holds a memory address.

Related

Why there is a data race [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
Improve this question
I was reading Dave Cheney's post https://dave.cheney.net/2015/11/18/wednesday-pop-quiz-spot-the-race, but couldn't understand why the example contains data race. Can someone explain it to me?
Here's the relevant code from the blog post:
func (rpc *RPC) compute() {
time.Sleep(time.Second)
rpc.result = 42 /* W */
close(rpc.done)
}
func (RPC) version() int {
return 1
}
⋮
go rpc.compute()
version := rpc.version() /* R */
<-rpc.done
The goroutine modifies the caller's rpc.result field at the line notated by /* W */. This is the easy part to understand.
The method call at the line notated by /* R */ is syntactic sugar for (*rpc).version(). The receiver value is copied on the method call, including the result field. The read is concurrent with the write at /* W */ and is therefore a data race. Although the program does not do anything with the copied result field, it's still a data race.
Fix by changing the version() method to use pointer receiver:
func (*RPC) version() int {
return 1
}

can you use a primitive or inbuild data types as a method in golang [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
i wanna know if we are able to use inbuild data types as a method for a func in golang, cause whenever I use it as such, it shows an error
You can define methods on built-in types by first wrapping them with your own types, like this:
type MyInteger int
func (my MyInteger) Tell() {
fmt.Println("I'm MyInteger with value", my)
}
func main() {
var my MyInteger = 42
my.Tell()
}
You can try this on the Go Playground, it will print:
I'm MyInteger with value 42
This can be useful if you want to make a built-in type implement an interface. For example, here's how MyInteger would implement the fmt.Stringer interface:
type MyInteger int
func (my MyInteger) String() string {
return "MyInteger " + strconv.Itoa(int(my))
}
func main() {
var my MyInteger = 42
fmt.Println(my)
}

Provide potentional nil variable to function in GOLANG [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to call a function with a int variable that can have a value or can be nil. In the main function i'm doing this call.
doDomething(10) // does not work?
doDomething(nil) // works
func doSomething(parent_id *int) {
fmt.Print(parent_id)
}
I'm getting the following error:
cannot use a (type int) as type *int in argument to doSomething
I use the *int pointer, therefore the nil works but not if it is a value. Then I'm getting the type mismatch.
doSomething expects a *intparameter. 10 is of type int, so this is he source of the error.
This is a valid usage:
i := 10
doDomething(&i)
This is how doSomething should look like:
func doSomething(parent_id *int) {
if parent_id == nil{
//nil
fmt.Println("nil")
return
}
//valid int
fmt.Printf("%d", *parent_id)
}

Multiple receivers on a single method [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Is it possible to have multiple receivers on a single function? In other words, a single function can belong to two or more structs?
Say I have
type Struct1 struct {
foo.Client
}
func CreateClient() struct1 {
return struct1{
ClientID: cId,
// ...
}
}
func (s *Struct1) MyFunc( // ... ) {}
But I also want to be able to associate MyFunc with another struct (different package):
type Struct2 struct {
lgr log.logger
}
func NewStruct2 (l *log.logger) (*Struct2, err) {
return &Struct2{mylog: *l}, nil
}
So what I want to actually have is:
func (s1 *Struct1, s2 *Struct2) MyFunc( // ... ) {}
"Is it possible to have multiple receivers on a single function?" -- It is not possible.
https://golang.org/ref/spec#Method_declarations
The receiver is specified via an extra parameter section preceding the
method name. That parameter section must declare a single non-variadic
parameter, the receiver.

How do I get the type of struct in Go? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am working on a demo project to understand GO language. I have defined one interface and 2 struct type. Also, I have defined an array of interfaces. Depending on the user input, I define each element within the array as a type of struct. During the data manipulation, I want to check the type of the struct defined on the array.
I have tried to use reflect, but unfortunately it did not worked. Also other methods on internet did not worked. I received messages such as panic or json cannot Unmarshal.
type Main_interface interface {
}
type Struct1 struct {
Index int
ID int
Name string
}
type Struct2 struct {
Index int
Timestamp string
Temporary_ID int
}
var MyArray []Main_interface
//...
NewStruct1Block := generateStruct1Block(...)
MyArray = append(MyArray, NewStruct1Block)
//...
NewStruct2Block := generateStruct2Block(...)
MyArray = append(MyArray, NewStruct2Block)
UPDATE: I want to be able to check the kind of struct implements the interface at runtime, depending on the user input.
Your array can be heteregenious, that is, it can contain elements of different types. You can't ensure (at compile time) that all elements are of the same type.
That said, you can check a single element using the type cast syntax.
You have three options:
Option 1: Check against a specific type
var unknown Main_Interface = getSomethingSomewhere()
result, ok := unknown.(Struct1);
if ok {
// result has type `Struct1`
}
Option 2: Use a switch statement to cover multiple types (already presented in another answer)
switch t := unknown.(type) {
case Struct1:
// t has type `Struct1` within this block (at compile time)
case Struct2:
// t has type `Struct2` within this block (at compile time)
default:
// neither Struct1 no Struct2
}
Option 3: compare against another type at runtime.
Note that types returned by reflect.TypeOf are comparable using the == operator, as documented here:
https://golang.org/pkg/reflect/#Type
Type values are comparable, such as with the == operator, so they can be used as map keys. Two Type values are equal if they represent identical types.
So we can do something like this:
var s1 Struct1 // empty struct
var s2 Struct2 // empty struct
if reflect.TypeOf(unknown) == reflect.TypeOf(s1) {
// unknown holds an s1 instance
}
But this is obviously not useful when you can just do the compile time check. Instead, you can compare two unknowns to check if they are the same:
var unknown1 Main_Interface = getSomethingSomewhere()
var unknown2 Main_Interface = getSomethingSomewhereElse()
if reflect.TypeOf(unknown1) == reflect.TypeOf(unknown2) {
// they are the same type
}
You need to use type assestion as below:
var MyArray []Main_interface
NewStruct1Block := Struct1{}
NewStruct2Block := Struct2{}
MyArray = append(MyArray, NewStruct1Block)
MyArray = append(MyArray, NewStruct2Block)
fmt.Printf("%v", MyArray)
switch t := MyArray[0].(type) {
case Struct1:
fmt.Printf("%v", t)
t.ID = 1
case Struct2:
fmt.Printf("%v", t)
t.Timestamp = "A"
default:
fmt.Print("unknown")
}
Working code here:
https://play.golang.org/p/OhpBDJu_q2x

Resources