美文网首页
10 | 面向对象

10 | 面向对象

作者: 刀斧手何在 | 来源:发表于2020-03-21 18:16 被阅读0次
  • 利用方法来模拟面向对象
type student struct{
    name string
    age int8
}
func (s *student) getName() string {
    return s.name
}
func TestClass(t *testing.T){
    stu := student{"fangle",20}
    t.Log(stu.getName())
}
//result : fangle

方法实际上也是函数,只是在声明时在关键字fun和方法之间增加一个参数,这个参数也称之为接收者。

  • 值接收者与指针接收者
type student struct{
    name string
    age int8
}
func (s student) setAge(age int8)  {
    s.age = age
}
func TestClass(t *testing.T){
    stu := student{}
    stu.setAge(21)
    t.Log(stu)
}
//result : {0  } 

值接收者得到了结构体的一份拷贝,方法内的操作不会影响调用者

type student struct{
    name string
    age int8
}
func (s *student) setAge(age int8)  {
    s.age = age
}
func TestClass(t *testing.T){
    stu := student{}
    stu.setAge(21)
    t.Log(stu)
}
//result : { 21}

指针接收者得到了结构体指针的一份拷贝,方法内操作会影响调用者

使用值接收者还是指针接收者,不应该由该方法是否修改了接收到到值来决定。这个决策应该基于该类型到本质

  • 方法的接收者可以是任意自定义类型
type text string
func (t *text) len() int{
    return len(*t)
}
func TestClass(t *testing.T){
    var msg text = "mysql gone away"
    t.Log(msg.len())
}
//result : 15
  • String魔术方法

组合

  • 允许结构体内嵌
type user struct {
    name string
    age int8
}
type vip struct {
    user
    level int8
}
func TestClass(t *testing.T){
    one := vip{
        user {
            name: "fangle",
            age:  20,
        },1,
    }
    t.Log(one,one.name,one.user.name)
}
//result : {{fangle 20} 1} fangle fangle
  • 利用结构体内嵌来实现组合
type header struct {
    meta string
    script string
}
type body struct {
    div string
    table string
    script string
}

type html struct {
    header
    body
    script string
}
func TestClass(t *testing.T){
    doc := html{
        header{"<meta>", "<script0>"},
        body{"<div>","<table>","<script1>"},
        "<script2>",
    }
    t.Log(doc,doc.script)
    t.Log(doc.header.script,doc.body.script)
}
//result :{{<meta> <script0>} {<div> <table> <script1>} <script2>} 
//<script2> <script0> <script1>

如果两个内嵌结构体之间有同名变量,不允许外层结构体直接访问变量,必须显示指定要访问的是那个内嵌结构体的变量

相关文章

  • 面向对象设计的 10 条戒律

    面向对象设计的 10 条戒律 面向对象设计的 10 条戒律

  • 10面向对象

    一.面向对象基础 #类的定义与调用 #定义类使用chass关键字,然后继承至object类、 #2.在类中定义方法...

  • 10 | 面向对象

    利用方法来模拟面向对象 方法实际上也是函数,只是在声明时在关键字fun和方法之间增加一个参数,这个参数也称之为接收...

  • face 10面向对象

    面向对象 请写出php的构造函数和析构函数 __construct() __destruct() 着重记忆php面...

  • PHP全栈学习笔记8

    面向对象的基本概念,面向对象编程,oop,面向对象,面向对象的分析,面向对象的设计,面向对象的编程,什么是类。 类...

  • PHP全栈学习笔记8

    面向对象的基本概念,面向对象编程,oop,面向对象,面向对象的分析,面向对象的设计,面向对象的编程,什么是类。 类...

  • 总结.Net基础知识——献给即将入坑的同行们(一期)

    什么是面向对象 面向对象OO = 面向对象的分析OOA + 面向对象的设计OOD + 面向对象的编程OOP; 通俗...

  • 面向对象基础

    面向对象编程包括: 面向对象的分析(OOA) 面向对象的设计(OOD) 面向对象的编程实现(OOP) 面向对象思想...

  • 20-OOP类与对象

    面向对象 Object Oriented 学习面向对象:XXOO 面向对象的学习: 面向过程和面向对象的区别: 面...

  • JavaScript面向对象核心知识归纳

    面向对象 概念 面向对象就是使用对象。面向对象开发就是使用对象开发。 面向过程就是用过程的方式进行开发。面向对象是...

网友评论

      本文标题:10 | 面向对象

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