Home >Backend Development >Golang >Set an int64 value to an *int64 pointer

Set an int64 value to an *int64 pointer

WBOY
WBOYforward
2024-02-10 09:06:22609browse

将 int64 值设置为 *int64 指针

php editor Xigua is here to introduce to you a problem about setting an int64 value to an int64 pointer. In programming, we often need to manipulate pointers to modify the value of variables. For variables of type int64, we can modify their values ​​by setting them to int64 pointers. This operation is very useful in certain situations and can help us process data more flexibly. Next, let us analyze this problem in detail and give corresponding sample code.

Question content

I need to map the structure to create a json structure. The collector_id attribute in json should be able to take null value or int value. I have the following code:

type purchaseInfo struct {
    CollectorID *int64 `json:"collector_id"`
}

func mapPurchaseInfo(collectorID int64) purchaseInfo {
    var collectorIDToSend *int64
    if collectorID < 0 {
        collectorIDToSend = nil
    } else {
        collectorIDToSend = collectorID
    }

    return purchaseInfo{
        CollectorID: collectorIDToSend,
    }
}

This code does not compile and collectorid cannot be assigned to collectoridtosend. Is there a way to do this?

Thanks!

Solution

  • In the declaration of the mappurchaseinfo function, in order to correctly assign the value passed in as the parameter to collectoridtosend, the & operator must be used to retrieve the memory address of the collectorid.
  • When constructing the purchaseinfo return variable, you can directly put it into the fields of the structure, as shown in the example.
type purchaseInfo struct {
        CollectorID *int64 `json:"collector_id"`
    }

    func mapPurchaseInfo(collectorID int64) purchaseInfo {
        var collectorIDToSend *int64
        if collectorID < 0 {
            collectorIDToSend = nil
        } else {
            collectorIDToSend = &collectorID
        }

        return purchaseInfo{
            CollectorID: collectorIDToSend,
        }
    }

The above is the detailed content of Set an int64 value to an *int64 pointer. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete