I have the function
func addCatsToMap(m map[string][]CatHouse, meowId int, treats Set, dog *Dog) {
//if (complicated thing) add Cat to m
}
Is it true that m, treats, and dog are passed-by-reference, and meowId has it's value copied.
Since m is map, its pass-by-reference.
Dog is a struct. So, I should pass the pointer to avoid copying the data.
Set is an interface, as defined here:
type Set interface {
Add(value string)
Contains(value string) (bool)
Length() (int)
RemoveDuplicates()
}
Is Set pass-by-value?
An interface type is simply a set of methods. Notice that the members of an interface definition do not specify whether or not the receiver type is a pointer. That is because the method set of a value type is a subset of the method set of its associated pointer type. That's a mouthful. What I mean is, if you have the following:
type Whatever struct {
Name string
}
and you define the following two methods:
func (w *Whatever) Foo() {
...
}
func (w Whatever) Bar() {
...
}
WhateverBar()*WhateverFoo()Bar()
type Grits interface {
Foo()
Bar()
}
*WhateverGritsWhateverWhateverFoo()
The following example illustrates a function that takes an interface type in both ways:
package main
import "fmt"
type Fruit struct {
Name string
}
func (f Fruit) Rename(name string) {
f.Name = name
}
type Candy struct {
Name string
}
func (c *Candy) Rename(name string) {
c.Name = name
}
type Renamable interface {
Rename(string)
}
func Rename(v Renamable, name string) {
v.Rename(name)
// at this point, we don't know if v is a pointer type or not.
}
func main() {
c := Candy{Name: "Snickers"}
f := Fruit{Name: "Apple"}
fmt.Println(f)
fmt.Println(c)
Rename(f, "Zemo Fruit")
Rename(&c, "Zemo Bar")
fmt.Println(f)
fmt.Println(c)
}
Raname(&f, "Jorelli Fruit")Rename(c, "Jorelli Bar")Fruit*FruitRenamable*CandyRenableCandy
这篇关于指针上的golang指针作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!