zoukankan      html  css  js  c++  java
  • Go

    Golang的结构体没有构造函数,通常可以使用工厂模式来解决这个问题;
     
    需求:
        当我们在model中定义结构体时,当结构体名称首字母大写Student 那么可以跨包使用,但是要是小写student,怎么办呢?这就需要使用工厂模式来解决:
        引包要从src的目录下开始,src不用写;
        示例:
            type student struct {    
                    Name  string     
                    score float64 
            }
            
            // 因为student结构体首字母是小写,因此是只能在model使用
            // 我们通过工厂模式来解决 
             // 定义一个方法 
             func NewStudent(name string, score float64) *student {     
                    // 根据参数 直接创建 student 实例然后返回     
                    return &student{         
                            Name:  name,         
                            score: score,     
                    } 
                }
     
                // 当 student 这个结构体首字母小写,我们可以使用工厂模式来实现创建实例    
                var stu = NewStudent("jack~", 99.5)   // &{jack~ 99.5}
     
        如果结构体的某个字段首字母小写呢?
            示例:
                // 如果结构体的字段 首字母也小写的话,也无法跨包使用
                // 我们可以提供一个方法 
                func (s *student) GetScore() float64 {     
                        return s.score 
                }
                
                // fmt.Println("name=", (*stu).Name, "score=", (*stu).GetScore)  // 正规的写法     
     
                fmt.Println("name=", stu.Name, "score=", stu.GetScore())  // name= jack~ score= 99.5
     
     
     
     
     
     
     
     
     
     
     
     
     
        
        
  • 相关阅读:
    真正的e时代
    在线手册
    UVA 10616 Divisible Group Sums
    UVA 10721 Bar Codes
    UVA 10205 Stack 'em Up
    UVA 10247 Complete Tree Labeling
    UVA 10081 Tight Words
    UVA 11125 Arrange Some Marbles
    UVA 10128 Queue
    UVA 10912 Simple Minded Hashing
  • 原文地址:https://www.cnblogs.com/guo-s/p/14067205.html
Copyright © 2011-2022 走看看