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
     
     
     
     
     
     
     
     
     
     
     
     
     
        
        
  • 相关阅读:
    python系列十二:python3模块
    python系列十一:python3数据结构
    python系列十:python3函数
    python系列九:python3迭代器和生成器
    python系列八:Python3条件控制&循环语句
    python系列七:Python3字典dict
    python系列六:Python3元组tuple
    Linux Ubuntu 安装SSH服务
    Linux Ubuntu 查看IP
    Linux 基础命令
  • 原文地址:https://www.cnblogs.com/guo-s/p/14067205.html
Copyright © 2011-2022 走看看