search
HomeBackend DevelopmentGolangAn article to help you understand the basic interface of Go language (Part 2)

The meaning of empty interface

This article introduces Storage class interface , storage interface is my name. In fact, others call it empty interface.

The function of the empty interface is to store any data.

Similarly, the empty interface does not define any methods, that is to say any Interfaces all implement empty interfaces, so empty interfaces can save any data.


Empty interface

##Empty interface sample code

package main

import "fmt"

func main() {
    //变量直接赋值为空接口
    var x interface{}
    x = 1
    x = 1.1
    x = "666"
    x = [3]int{1, 2, 3} //数组
    x = []int{6, 23}    //切片
    x = map[string]string{
        "Name": "张三",
        "Age":  "666",
}
    fmt.Println(x)
    //map中value类型为空接口
    var y = map[string]interface{}{
        "Name":"张三",
        "Age":18,
}
    fmt.Println(y)
}

Execution results

An article to help you understand the basic interface of Go language (Part 2)

##The empty interface can indeed store any data and can be used directly.


空接口在函数中的应用

不知道你有没有想过,如果函数的参数,也是一个空接口,那不是就可以随便传值了吗?

我还用个毛静态类型,以后都用空接口得了,嗯。。。这个按下不表,等会说。


函数参数为空接口代码

package main
import "fmt"

func say(x interface{}) {
    fmt.Println(x)
}
func main() {
    say(1)
    say("666")
    say([]int{5, 1, 3})
}

确实是如上述所说,函数参数为空接口类类型,的确可以传任何数据。

但是仅限打印时可以随便打印。

假设我想让传入的值+1

func say(x interface{}) {
    fmt.Println(x)
    fmt.Println(x+1)
}

报错信息

An article to help you understand the basic interface of Go language (Part 2)

所以说,空接口并不是万能的。


类型断言

上述函数虽然可以接收任意类型。

但是我有个需求。

如果传入的是int类型,参数+100。

如果传入的是字符串类型,参数+"666"。

如果传入的是其他类型,返回不存在。

这该怎么办呢?这就要用到断言这个功能。

断言语法

空接口.(类型)

示例代码

func say(x interface{}) {
    value, ok := x.(int)
    if ok {
        //如果是ok表示断言成功,是int类型
        fmt.Println(value + 100)
}
    value2, ok := x.(string)
    if ok {
        //断言成功表示是字符串
        fmt.Println(value2 + "666")
  }
}

如果说有很多类型,断言起来比较麻烦,这时候用switch比较好。

func say(x interface{}) {
    switch value := x.(type) {
    case int:
        fmt.Println(value + 10)
    case string:
        fmt.Println(value + "666")
    default:
        fmt.Println("啥都不是")
  }
}
//case可以继续写,可以写很多很多

执行结果

An article to help you understand the basic interface of Go language (Part 2)


总结

到此为止,Go语言的接口是全部都讲完了。

接口主要分为行为接口存储接口

  • 行为接口主要用在面向对象这个方向,规定父类必须有哪些动作。

  • 空接口时为了方便存值,可以存储任意类型。

The above is the detailed content of An article to help you understand the basic interface of Go language (Part 2). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools