错误验证被递增和复制

huangapple go评论150阅读模式
英文:

Error validation is incremented and duplicated

问题

一种方法是将valid变量声明为全局变量,然后在每个函数中直接使用它,而不是重新声明一个新的变量。这样就可以避免重复和增加结果。以下是修改后的代码示例:

var valid validation.Validation

func validationInit() validation.Validation {
    valid = validation.Validation{}
    return valid
}

func AddClub(name string) (id int64, error []*validation.ValidationError) {
    club := Club{Name: name}
    // 直接使用全局变量 valid
    valid = validation.Validation{}
    // 其他代码...
}

这样,你就可以在不重复和增加结果的情况下重复使用 valid 变量。

英文:

Somehow my error validations are duplicated when I use valid global variable like below

var (
	valid validation.Validation
)

func validationInit() validation.Validation {
	valid := validation.Validation{}
	return valid
}

But when I move valid := validation.Validation{} to my model function it works fine without any duplicates like below:

func AddClub(name string) (id int64, error []*validation.ValidationError) {
	club := Club{Name: name}
	valid := validation.Validation{}

How am I able to not duplicate this valid across each function but reuse variable without results being incremented and duplicated?

答案1

得分: 1

由于您的validationInit()函数返回的是一个validation.Validation的值,而不是指向它的指针,所以您不能从多个函数或同一函数的多次调用中返回相同的全局变量。

如果您真的想要这样做,您必须返回指向全局变量的指针,否则将返回全局变量值的副本。

示例:

var valid validation.Validation

func someFunc() *valid.Validation {
    // 您可以在这里访问全局变量valid,也可以修改它
    return &valid
}

但这很可能不是您想要的。这样做将不允许您在函数返回的同时拥有两个不同的validation.Validation值。

我建议您省略全局变量,每次需要时只创建一个新的validation.Validation值,并返回该新值(可以是值或指向它的指针)。

英文:

Since your validationInit() func returns a validation.Validation value and not a pointer to it, you cannot return the same global variable from multiple functions or from multiple invocations of the same function.

If you really want this, you have to return a pointer to the global variable, else a copy of the value of the global variable will be returned.

Example:

var valid validation.Validation

func someFunc() *valid.Validation {
    // You can access the global variable valid here, you can also modify it
    return &valid
}

But this is most likely not what you want. This would not allow you to have 2 different validation.Validation values exist at the same time returned by your functions.

I suggest you to leave out the global variable, and just create a new validation.Validation value each time it is needed and return that new value (either by value or a pointer to it).

huangapple
  • 本文由 发表于 2015年1月12日 23:13:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/27905131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定