美文网首页golang从零起步
使用结构体的3中方式

使用结构体的3中方式

作者: 次序 | 来源:发表于2018-08-20 16:20 被阅读0次
    package main
    
    import (
        "fmt"
        "strings"
    )
    
    type Person struct {
        firstName string
        lastName string
    }
    func upPerson(p *Person) {
        p.firstName = strings.ToUpper(p.firstName)
        p.lastName = strings.ToUpper(p.lastName)
    }
    //使用结构体的3中方式
    func main() {
        // 1-struct as a value type:
        var pers1 Person
        pers1.firstName = "Chris"
        pers1.lastName = "Woodward"
        upPerson(&pers1)
        fmt.Printf("The name of the person is %s %s\n", pers1.firstName, pers1.lastName)
        // 2—struct as a pointer:
        pers2 := new(Person)
        pers2.firstName = "Chris"
        pers2.lastName = "Woodward"
        (*pers2).lastName = "Woodward" // 这是合法的
        upPerson(pers2)
        fmt.Printf("The name of the person is %s %s\n", pers2.firstName, pers2.lastName)
        // 3—struct as a literal:
        pers3 := &Person{"Chris","Woodward"}
        upPerson(pers3)
        fmt.Printf("The name of the person is %s %s\n", pers3.firstName, pers3.lastName)
    }
    

    相关文章

      网友评论

        本文标题:使用结构体的3中方式

        本文链接:https://www.haomeiwen.com/subject/qiyliftx.html