英文:
Create an object on method
问题
当我在方法中创建一个自身对象时,这是一个糟糕的代码吗?就像这样(看一下Create方法):
package main
import (
"fmt"
)
type SelfInitialisator struct {
Fields1, Fields2 string
}
func (rcv *SelfInitialisator) Method1() {
fmt.Println(rcv.Fields1, rcv.Fields2)
}
func (rcv *SelfInitialisator) CreateObject() {
s := new(SelfInitialisator)
s.Fields1 = "Hello"
s.Fields2 = "Foo"
}
func main() {
s := new(SelfInitialisator)
s.CreateObject()
}
这段代码中,在CreateObject
方法中创建自身对象是不好的实践。因为在方法内部创建的对象s
只在方法作用域内有效,方法执行完毕后,对象s
将被销毁,不会对外部产生任何影响。如果你想要在方法中创建对象并对其进行操作,可以将对象作为方法的参数传递进去,或者使用指针接收者来修改对象的属性。
英文:
It is a bad code when I create a self obeject on the method? Like this(Look at the method Create)
package main
import (
"fmt"
)
type SelfInitialisator struct {
Fields1, Fields2 string
}
func (rcv *SelfInitialisator) Method1() {
fmt.Println(rcv.Fields1, rcv.Fields2)
}
func (rcv *SelfInitialisator) CreateObject() {
s := new(SelfInitialisator)
s.Fields1 = "Hello"
s.Fields2 = "Foo"
}
func main() {
s := new(SelfInitialisator)
s.CreateObject()
}
答案1
得分: 4
在这段代码中,你创建了一个内存对象,然后将其丢弃并创建另一个对象,这样效率不高。而且你没有返回它。
Go语言的做法是使用一个函数来创建对象,像这样:
func NewSelfInitialisator() *SelfInitialisator {
s := new(SelfInitialisator)
s.Fields1 = "Hello"
s.Fields2 = "Foo"
return s
}
然后调用:
s := NewSelfInitialisator()
英文:
In this code you are creating a memory object, then throwing it away and creating another one which is rather inefficient. You also aren't returning it.
s := new(SelfInitialisator)
s.CreateObject()
The Go way would be to use a function to create your object, like this
func NewSelfInitialisator() *SelfInitialisator {
s := new(SelfInitialisator)
s.Fields1 = "Hello"
s.Fields2 = "Foo"
return s
}
And call
s := NewSelfInitialisator()
答案2
得分: 1
它不会改变接收器,只会创建另一个实例,该实例将在CreateObject()调用结束时丢失。
您可以直接使用接收器来初始化其内容:
func (rcv *SelfInitialisator) CreateObject() {
rcv.Fields1 = "Hello"
rcv.Fields2 = "Foo"
}
英文:
It wouldn't mutate the receiver, only create another instance which would be lost at the end of CreateObject() call.
You could use the receiver directly to initialize its content:
func (rcv *SelfInitialisator) CreateObject() {
rcv.Fields1 = "Hello"
rcv.Fields2 = "Foo"
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论