美文网首页
go中的type关键字

go中的type关键字

作者: 多啦A梦的野比大雄 | 来源:发表于2020-05-04 22:43 被阅读0次

go中的type关键字用来标识类型。
“类型”可以是普通类型、复合类型,也可以自定义。

  1. 普通类型
    boolean, int, string 等等。如
type Age int8
age := Age(8.00)
fmt.Println(age)

打印出

8
  1. 复合类型(struct, map, interface, pointer, function...)
  • struct
type Book struct {
     title string
     author string
     year string
     isbn string
}
  • interface
type ReadWrite interface {
      read()
      write(b []byte)
}

使用示例

package main

import (
    "fmt"
    "io/ioutil"
)

type File struct{
    file string
}

type ReadWrite interface {
    Read()
    Write(b []byte)
}

func (f File) Read(){
    data,err := ioutil.ReadFile(f.file)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(string(data))
}

func (f File) Write(b []byte) {
    ioutil.WriteFile(f.file, b, 0777)
}

func main() {
    var reader=File{"data.txt"}
    reader.Read()
    reader.Write([]byte("this is added data"))
    reader.Read()
}

打印出

this is test data
this is added data

type interface定义一个接口,实现了接口中的方法就继承了接口。

相关文章

  • 【go语言学习】type关键字

    type是go语法里的重要而且常用的关键字,type绝不只是对应于C/C++中的typedef。搞清楚type的使...

  • Go语言之type关键字

    type是go语法里的重要而且常用的关键字,type绝不只是对应于c/c++中的typedef。搞清楚type的使...

  • go中的type关键字

    go中的type关键字用来标识类型。“类型”可以是普通类型、复合类型,也可以自定义。 普通类型boolean, i...

  • Go Type

    Go语言中type关键字用于定义类型,因此又称为类型别名。 Go语言中的type并不对应着C/C++语言中的typ...

  • Golang关键字--type 类型定义

    参考Go关键字--type,原文除类型定义外,还介绍了type其它几种使用场合。本文只说类型定义。 type有如下...

  • go type关键字

    [TOC]type有几种用法:定义结构体,定义接口, 类型别名, 类型定义, 类型开关 定义结构体 结构体是由一系...

  • 【Golang 基础】Go 语言的数组

    Go 语言中的数组 定义数组的格式:var [n], 其中 n >= 0; 通过 new 关键字声...

  • Go语言 type关键字

    type有几种用法:定义结构体,定义接口, 类型别名, 类型定义, 类型开关 定义结构体结构体是由一系列具有相同...

  • 10 结构体struct

    Go 中的struct与C中的struct非常相似,并且Go没有class使用 type struc...

  • go入门(二)

    本文以面向对象为基础,阐述一下go中的某些功能的使用。 高级数据类型 高级数据的关键字是type。下面简单描述每种...

网友评论

      本文标题:go中的type关键字

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