Set an int64 value to an *int64 pointer

WBOY
Release: 2024-02-10 09:06:22
forward
586 people have browsed it

将 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,
    }
}
Copy after login

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,
        }
    }
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!