在左侧进行nil检查和在右侧进行nil检查之间有什么区别?

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

Any difference between nil check left on right

问题

这个函数接受两个字符串作为参数,并返回一个结构体或nil。我在这个函数内部定义了一个结构体,只用于这个函数。

type OrgFundingsDetailsFCT struct {
	ID           int     `db:"id"`
	OrgProfileID int     `db:"org_profile_id"`
	OrgID        int     `db:"org_id"`
	RefID        string  `db:"ref_id"`
	AmountUSD    float64 `db:"amount_usd"`
	FundingDate  string  `db:"funding_date"`
	Status       string  `db:"status"`
	Round        string  `db:"round"`
	CreatedBy    string  `db:"created_by"`
}
func (s *Server) getCompareOrgFundingsByRefID(refID, status string) (*OrgFundingsDetailsFCT, error) {
	type orgFunding struct {
		RefID  string `db:"ref_id"`
		Status string `db:"status"`
	}

	var orgFundingsDetailsFCT OrgFundingsDetailsFCT

	orgfunding := orgFunding{
		RefID:  refID,
		Status: status,
	}

	const query = `SELECT id,
					org_profile_id,
					org_id,
					ref_id,
					amount_usd,
					funding_date,
					status,round, 
					created_by 
					FROM org_fundings 
					WHERE ref_id=:ref_id AND status=:status`

	if err := s.db.NamedGet(&orgFundingsDetailsFCT, query, orgfunding); err == sql.ErrNoRows {
		s.logger.Infof("empty rows! getCompareOrgFundingsByRefID #111 %+v", err)
		return nil, nil
	} else if err != nil {
		s.logger.Infof("errors found! getCompareOrgFundingsByRefID#111  %+v", err)
		return nil, err
	}
	return &orgFundingsDetailsFCT, nil
}

现在我正在检查这个函数是否返回nil,像这样:

if nil != orgFundingsRefIdPending{
// 逻辑
}

但我的问题是,如果我这样检查,是否相同?

if orgFundingsRefIdPending != nil{
// 逻辑
}

如果nil在左边,与我的结果进行比较,或者我的结果在左边,与nil进行比较,这两种情况是相同的吗?这是否意味着如果我在任一侧放置nil,结果是相同的?另外,如果我只在函数内部使用结构体,这是有效的吗?

英文:

This is function takes two strings and returns struct or nil and I wrote a struct inside this function for use only this function.

type OrgFundingsDetailsFCT struct {
	ID           int     `db:"id"`
	OrgProfileID int     `db:"org_profile_id"`
	OrgID        int     `db:"org_id"`
	RefID        string  `db:"ref_id"`
	AmountUSD    float64 `db:"amount_usd"`
	FundingDate  string  `db:"funding_date"`
	Status       string  `db:"status"`
	Round        string  `db:"round"`
	CreatedBy    string  `db:"created_by"`
}
func (s *Server) getCompareOrgFundingsByRefID(refID, status string) (*OrgFundingsDetailsFCT, error) {
	type orgFunding struct {
		RefID  string `db:"ref_id"`
		Status string `db:"status"`
	}

	var orgFundingsDetailsFCT OrgFundingsDetailsFCT

	orgfunding := orgFunding{
		RefID:  refID,
		Status: status,
	}

	const query = `SELECT id,
					org_profile_id,
					org_id,
					ref_id,
					amount_usd,
					funding_date,
					status,round, 
					created_by 
					FROM org_fundings 
					WHERE ref_id=:ref_id AND status=:status`

	if err := s.db.NamedGet(&orgFundingsDetailsFCT, query, orgfunding); err == sql.ErrNoRows {
		s.logger.Infof("empty rows! getCompareOrgFundingsByRefID #111 %+v", err)
		return nil, nil
	} else if err != nil {
		s.logger.Infof("errors found! getCompareOrgFundingsByRefID#111  %+v", err)
		return nil, err
	}
	return &orgFundingsDetailsFCT, nil
}

Now I'm checking if this function return nil like this

    if nil != orgFundingsRefIdPending{
// logic
}

But my question is if I check like that is it same or not?

    if orgFundingsRefIdPending != nil{
//logic
}

If nil left side and check with my result is right side OR, my result is left side and check with nil is right side, Is it same? Does that mean the same thing happens if I put ‍‍‍‍‍‍nil on either side? also if I use struct on use only function is it valid thing?

答案1

得分: 5

getCompareOrgFundingsByRefID()函数返回一个指针和一个error值。要检查返回值(指针)是否为nil,只需将其与nil进行比较,例如:

var refID, status string
// 设置输入参数
orgFundingsRefIdPending, err := getCompareOrgFundingsByRefID(refID, status)
if err != nil {
    // 处理错误
}
if orgFundingsRefIdPending != nil {
    // 使用orgFundingsRefIdPending
}

==!=比较运算符只有在对它们的操作数进行求值后才能执行(它们的结果只能确定)。此外,由于这些比较运算符是_自反的_(意味着a == b只有在b == a时为true),顺序无关紧要。因此,a == bb == a是等价的。

如果运算符不是自反的(例如<,所以a < bb < a不同),或者如果不是所有操作数都需要用于其结果,那么顺序可能很重要,例如逻辑或(||),因为我们知道如果||的任何操作数为true,则结果为true,而不管其他值如何。由于Go的||运算符使用短路求值(如果在评估所有操作数之前已知结果,则不会评估其余操作数,从左到右进行),所以在||的情况下顺序很重要。例如,在f() || g()中,如果f()返回true,则不会调用g()函数。

注意:回到你的情况,如果返回的指针不是nil,但你想检查指向的结构体值是否为其类型的零值,你可以将其与OrgFundingsDetailsFCT{}进行比较:

if orgFundingsRefIdPending != nil {
    // 使用orgFundingsRefIdPending
    // 它是零值吗?
    if *orgFundingsRefIdPending == (OrgFundingsDetailsFCT{}) {
        // 它是零值
    }
}

有关详细信息和更多选项,请参阅https://stackoverflow.com/questions/28447297/how-to-check-for-an-empty-struct/28449449#28449449

英文:

The getCompareOrgFundingsByRefID() function returns a pointer and an error value. To check if the return value (the pointer) is nil, simply compare it to nil, e.g.:

var refID, status string
// Set input params
orgFundingsRefIdPending, err := getCompareOrgFundingsByRefID(refID, status)
if err != nil {
     // Handle error
}
if orgFundingsRefIdPending != nil {
    // Use orgFundingsRefIdPending
}

The == and != comparison operators can only be executed (their result can only be determined) if both of their operands are evaluated. Moreover, since these comparison operators are reflexive (meaning a == b is true only and only if b == a), the order does not matter. So a == b and b == a are equivalent.

The order matters if the operator would not be reflexive (e.g. < so a < b is not the same as b < a), or it could matter if not all operands would be needed for its result, such as the logical OR (||), because we know that if any of the operands of || is true, the result is true regardless of the other value. And since Go's || operator uses short-circuit evaluation (if the result is known before evaluating all operands, the rest are not evaluated, going from left-to-right), the order does matter in case of ||. E.g. in f() || g() if f() returns true, the g() function will not be called.

Note: Back to yoru case, if the returned pointer is not nil but you want to check if the pointed struct value is the zero value of its type, you may simply compare it to OrgFundingsDetailsFCT{}:

if orgFundingsRefIdPending != nil {
    // Use orgFundingsRefIdPending
    // Is it the zero value?
    if *orgFundingsRefIdPending == (OrgFundingsDetailsFCT{}) {
        // It's the zero value
    }
}

For details and more options, see https://stackoverflow.com/questions/28447297/how-to-check-for-an-empty-struct/28449449#28449449

huangapple
  • 本文由 发表于 2021年12月23日 15:02:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/70458722.html
匿名

发表评论

匿名网友

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

确定