Go 自学:变量、函数、结构体、接口、错误处理
1. 打印变量数据类型
package mainimport "fmt"func main() {penniesPerText := 2.0fmt.Printf("The type of penniesPerText is %T\n", penniesPerText)
}
输出为:
The type of penniesPerText is float64
2. 同时给多个变量赋值
package mainimport "fmt"func main() {averageOpenRate, displayMessage := .23, "is the average open rate of your message."fmt.Println(averageOpenRate, displayMessage)
}
3. 条件句
package mainimport "fmt"func main() {messageLen := 10maxMessageLen := 20fmt.Println("Trying to send message of length:", messageLen, "and a max length of:", maxMessageLen)if messageLen <= maxMessageLen {fmt.Println("Message sent")} else {fmt.Println("Message not sent")}
}
输出为:
Trying to send message of length: 10 and a max length of: 20
Message sent
4. 忽略返回值
注意:Go不允许存在未经使用的变量。使用“_”忽略函数返回值。
package mainimport "fmt"func main() {firstName, _ := getNames()fmt.Println("Welcome to Earth,", firstName)}func getNames() (string, string) {return "John", "Doe"
}
5. STRUCTS
我们使用struct去建立一个key-value的结构。
package mainimport "fmt"type messageToSend struct {phoneNumber intmessage string
}func test(m messageToSend) {fmt.Printf("Sending message: '%s' to: %v\n", m.message, m.phoneNumber)
}func main() {test(messageToSend{phoneNumber: 148255510981,message: "Thanks for signing up",})}
6. Embedded STRUCTS
embedded struct可以实现类似继承的效果。
package mainimport "fmt"type sender struct {rateLimit intuser
}type user struct {name stringnumber int
}func test(s sender) {fmt.Println("Sender name: ", s.name)fmt.Println("Sender number: ", s.number)fmt.Println("Sender rate limit: ", s.rateLimit)
}func main() {test(sender{rateLimit: 10000,user: user{name: "Deborah",number: 18055558790,},})
}
7. STRUCTS method
package mainimport "fmt"type authenticationInfo struct {username stringpassword string
}func (authI authenticationInfo) getBasicAuth() string {return fmt.Sprintf("Authorization: Basic %s:%s", authI.username, authI.password)
}func test(authInfo authenticationInfo) {fmt.Println(authInfo.getBasicAuth())
}func main() {test(authenticationInfo{username: "Bing",password: "98725",})
}
8. Interface接口
接口可以让我们将不同的类型绑定到一组公共的方法上,从而实现多态和灵活的设计。
package mainimport ("fmt""time"
)func sendMessage(msg message) {fmt.Println(msg.getMessage())
}type message interface {getMessage() string
}type birthdayMessage struct {birthdayTime time.TimerecipientName string
}func (bm birthdayMessage) getMessage() string {return fmt.Sprintf("Hi %s, it is your birthday on %s", bm.recipientName, bm.birthdayTime)
}type sendingReport struct {reportName stringnumberOfSends int
}func (sr sendingReport) getMessage() string {return fmt.Sprintf("Your '%s' report is ready. You've sent %v messages.", sr.reportName, sr.numberOfSends)
}func test(m message) {sendMessage(m)
}func main() {test(sendingReport{reportName: "First Report",numberOfSends: 10,})test(birthdayMessage{recipientName: "John Doe",birthdayTime: time.Date(1994, 03, 21, 0, 0, 0, 0, time.UTC),})
}
输出为:
Your ‘First Report’ report is ready. You’ve sent 10 messages.
Hi John Doe, it is your birthday on 1994-03-21 00:00:00 +0000 UTC
Interface接口的另一个例子
package mainimport ("fmt"
)type employee interface {getName() stringgetSalary() int
}type contractor struct {name stringhourlyPay inthoursPerYear int
}func (c contractor) getName() string {return c.name
}func (c contractor) getSalary() int {return c.hourlyPay * c.hoursPerYear
}type fullTime struct {name stringsalary int
}func (f fullTime) getName() string {return f.name
}func (f fullTime) getSalary() int {return f.salary
}func test(e employee) {fmt.Println(e.getName(), e.getSalary())
}func main() {test(fullTime{name: "Jack",salary: 50000,})test(contractor{name: "Bob",hourlyPay: 100,hoursPerYear: 73,})
}
输出为:
Jack 50000
Bob 7300
9. 实现多个Interface
package mainimport ("fmt"
)type expense interface {cost() float64
}type printer interface {print()
}type email struct {isSubscribed boolbody string
}func (e email) cost() float64 {if !e.isSubscribed {return 0.05 * float64(len(e.body))}return 0.01 * float64(len(e.body))
}func (e email) print() {fmt.Println(e.body)
}func test(e expense, p printer) {fmt.Printf("Printing with cost: %f\n", e.cost())p.print()fmt.Println("================================")
}func main() {e := email{isSubscribed: true,body: "hello there",}test(e, e)e = email{isSubscribed: false,body: "I want my money back",}test(e, e)
}
10. Type assertions类型断言
通过这一行代码“em, ok := e.(email)”,检查输入是否为email。
通过这一行代码“s, ok := e.(sms)”,检查输入是否为sms。
package mainimport ("fmt"
)type expense interface {cost() float64
}func getExpenseReport(e expense) (string, float64) {em, ok := e.(email)if ok {return em.toAddress, em.cost()}s, ok := e.(sms)if ok {return s.toPhoneNumber, s.cost()}return "", 0.0
}type email struct {isSubscribed boolbody stringtoAddress string
}type sms struct {isSubscribed boolbody stringtoPhoneNumber string
}func (e email) cost() float64 {if !e.isSubscribed {return float64(len(e.body)) * .05}return float64(len(e.body)) * .01
}func (s sms) cost() float64 {if !s.isSubscribed {return float64(len(s.body)) * .1}return float64(len(s.body)) * .03
}func test(e expense) {fmt.Println(getExpenseReport(e))
}func main() {test(email{isSubscribed: true,body: "hello there",toAddress: "john@dose.com",})test(sms{isSubscribed: false,body: "This meeting could have been an email",toPhoneNumber: "+155555509832",})
}
11. Type Switches
可以利用switch语法改写以上代码,令程序可以根据不同输入类型,有不一样的输出。
func getExpenseReport(e expense) (string, float64) {switch v := e.(type) {case email:return v.toAddress, v.cost()case sms:return v.toPhoneNumber, v.cost()default:return "", 0.0}
}
12. 如何处理error
package mainimport ("fmt"
)func sendSMSToCouple(msgToCustomer, msgToSpouse string) (float64, error) {costForCustomer, err := sendSMS(msgToCustomer)if err != nil {return 0.0, err}costForSpouse, err := sendSMS(msgToSpouse)if err != nil {return 0.0, err}return costForCustomer + costForSpouse, nil
}func sendSMS(message string) (float64, error) {const maxTextLen = 25const costPerchar = .0002if len(message) > maxTextLen {return 0.0, fmt.Errorf("can't send texts over %v characters", maxTextLen)}return costPerchar * float64(len(message)), nil
}func test(msgToCustomer, msgToSpouse string) {defer fmt.Println("=========")fmt.Println("Message for customer:", msgToCustomer)fmt.Println("Message for spouse:", msgToSpouse)totalCost, err := sendSMSToCouple(msgToCustomer, msgToSpouse)if err != nil {fmt.Println("Error:", err)return}fmt.Printf("Total cost: $%.4f\n", totalCost)
}func main() {msgToCustomer_1 := "Thank you."msgToSpouse_1 := "Enjoy!"test(msgToCustomer_1, msgToSpouse_1)msgToCustomer_1 = "We loved having you in."msgToSpouse_1 = "We hope the rest of your evening is absolutely interesting."test(msgToCustomer_1, msgToSpouse_1)
}
输出为:
Message for customer: Thank you.
Message for spouse: Enjoy!
Total cost: $0.0032
Message for customer: We loved having you in.
Message for spouse: We hope the rest of your evening is absolutely interesting.
Error: can’t send texts over 25 characters
相关文章:
Go 自学:变量、函数、结构体、接口、错误处理
1. 打印变量数据类型 package mainimport "fmt"func main() {penniesPerText : 2.0fmt.Printf("The type of penniesPerText is %T\n", penniesPerText) }输出为: The type of penniesPerText is float64 2. 同时给多个变量赋值 package mai…...

pyqt Pyton VTK 使用 滑块 改变 VTK Actor 颜色
使用 PyQt5 vtk vtk球体 使用滑块 RGB 改变 Actor 颜色 CODE import sys from PyQt5.QtWidgets import * from PyQt5.QtWidgets import (QApplication, QCheckBox, QGridLayout, QGroupBox,QMenu, QPushButton, QRadioButton, QVBoxLayout, QWidget, QSlider,QLineEdit,QLabe…...

春秋云镜 CVE-2019-16113
春秋云镜 CVE-2019-16113 Bludit目录穿越漏洞 靶标介绍 在Bludit<3.9.2的版本中,攻击者可以通过定制uuid值将文件上传到指定的路径,然后通过bl-kernel/ajax/upload-images.php远程执行任意代码。 启动场景 漏洞利用 exp https://github.com/Kenun…...

【JavaEE基础学习打卡06】JDBC之进阶学习PreparedStatement
目录 前言一、PreparedStatement是什么二、重点理解预编译三、PreparedStatement基本使用四、Statement和PreparedStatement比较1.PreparedStatement效率高2.PreparedStatement无需拼接参数3.PreparedStatement防止SQL注入 总结 前言 📜 本系列教程适用于JavaWeb初学…...
Postgresql12基于时间点恢复
1、环境 centos 7系统 postgresql 12 docker 20.10.6 2、整体思路 1)进行一个pgdata目录的全量备份 2)通过wal日志恢复到故障发生之前某个时间点 3、操作步骤 配置postgresql.conf文件 #日志级别 wal_level replica #归档开关 archive_mode on …...

【MySQL系列】Select语句单表查询详解(二)ORDERBY排序
💐 🌸 🌷 🍀 🌹 🌻 🌺 🍁 🍃 🍂 🌿 🍄🍝 🍛 🍤 📃个人主页 :阿然成长日记 …...
C++学习第十九天----简单文件输入/输出和今日工作问题
1.写入到文本文件中 cout用于控制台输出; 必须包含头文件iostream; 头文件iostream定义了一个用于处理输出的ostream类; 头文件iostream声明了一个名为cout的ostream变量(对象); 必须指明名称空间std&…...

基于风险的漏洞管理
基于风险的漏洞管理涉及对即将被利用的漏洞的分类响应,如果被利用,可能会导致严重后果。本文详细介绍了确定漏洞优先级时要考虑的关键风险因素,以及确保基于风险的漏洞管理成功的其他注意事项。 什么是基于风险的漏洞管理对基于风险的漏洞管…...
命令行——Git基本操作总结
介绍 我们的操作使用的是客户端TortoiseGit 操作的git ,实际上底层依旧是使用的命令行帮我们执行, 在早期 git 并没有窗口化工具,开发人员只能使用命令行模式 实际上,如果你掌握并熟练使用了命令行模式操作git 的话,你会发现某些操作命令行比窗口化操作要简单 所有你在工作中…...

验证评估守护关基安全 赛宁数字孪生靶场创新实践
近日,由赛宁网安主办,ISC互联网安全大会组委会协办的第十一届互联网安全大会(ISC 2023)安全运营实践论坛圆满结束。赛宁网安产品总监史崯出席并作出主题演讲:《基于数字孪生靶场如何开展验证评估》,同时…...
R语言09-R语言中的字符函数和分布相关函数
字符函数 paste() 和 paste0(): 将多个字符向量连接成一个字符串,paste0() 直接连接,而 paste() 可以通过 sep 参数指定分隔符。 vector1 <- c("Hello", "world") vector2 <- c("R", "programming") re…...

pnpm无法加载文件 (解决方法 )
现在要运行一个TS的项目,我的电脑上没有安装pnpm,导致我的vscode一直报错无法加载。 pnpm安装: npm install -g pnpm pnpm : 无法加载文件 pnpm : 无法加载文件 C:\Users\HP\AppData\Roaming\npm\pnpm.ps1,因为在此系统上禁止运…...

做一个蛋糕店小程序需要哪些步骤?
对于一些不懂技术的新手来说,创建蛋糕店小程序可能会感到有些困惑。但是,有了乔拓云平台的帮助,你可以轻松地创建自己的蛋糕店小程序。下面,我将为大家详细介绍一下具体的操作步骤。 首先,登录乔拓云平台并进入后台管理…...

Docker的革命:容器技术如何重塑软件部署之路
引言 在过去的几年中,容器技术已经从一个小众的概念发展成为软件开发和部署的主流方法。Docker,作为这一变革的先驱,已经深深地影响了我们如何构建、部署和运行应用程序。本文将探讨容器技术的起源,Docker如何崛起并改变了软件部…...

【ARM-Linux】项目,语音刷抖音项目
文章目录 所需器材装备操作SU-03T语音模块配置代码(没有用wiring库,自己实现串口通信)结束 所需器材 可以百度了解以下器材 orangepi-zero2全志开发板 su-03T语音识别模块 USB-TTL模块 一个安卓手机 一根可以传输的数据线 装备操作 安…...
Linux驱动开发:技术、实践与Linux的历史
一、引言 Linux,这个开源的操作系统,已经在全球范围内赢得了开发者和企业的广泛支持。它的强大之处在于其内核以及无数的驱动程序,这些驱动程序使得各种硬件设备可以在Linux操作系统上运行。本篇文章将深入探讨Linux驱动开发,包括…...
# Go学习-Day5
文章目录 map增加和更新删除查询遍历(for-range)map切片关于哈希表遍历的一点看法对map的key排序 结构体与OOP声明、初始化、序列化方法工厂模式 个人博客:CSDN博客 map map是一个key-value的数据结构,又称为字段或关联数组 Gol…...

创建型(二) - 单例模式
一、概念 单例设计模式(Singleton Design Pattern):一个类只允许创建一个对象(或者实例),那这个类就是一个单例类。 优点:在内存里只有一个实例,减少了内存的开销,避免…...

基于swing的图书借阅管理系统java jsp书馆书籍信息mysql源代码
本项目为前几天收费帮学妹做的一个项目,Java EE JSP项目,在工作环境中基本使用不到,但是很多学校把这个当作编程入门的项目来做,故分享出本项目供初学者参考。 一、项目描述 基于swing的图书借阅管理系统 系统有2权限࿱…...

Android相机-HAL-Rockchip-hal3
引言: 对于Android相机的 HAL层而言对上实现一套Framework的API接口,对下通过V4L2框架实现与kernel的交互。不同的平台会有不同的实现方案。主要是对Android HAL3的接口的实现。看看rockchip是怎么支持hal3的? 代码目录: hardw…...

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型
摘要 拍照搜题系统采用“三层管道(多模态 OCR → 语义检索 → 答案渲染)、两级检索(倒排 BM25 向量 HNSW)并以大语言模型兜底”的整体框架: 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后,分别用…...

接口测试中缓存处理策略
在接口测试中,缓存处理策略是一个关键环节,直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性,避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明: 一、缓存处理的核…...

第19节 Node.js Express 框架
Express 是一个为Node.js设计的web开发框架,它基于nodejs平台。 Express 简介 Express是一个简洁而灵活的node.js Web应用框架, 提供了一系列强大特性帮助你创建各种Web应用,和丰富的HTTP工具。 使用Express可以快速地搭建一个完整功能的网站。 Expre…...

大数据零基础学习day1之环境准备和大数据初步理解
学习大数据会使用到多台Linux服务器。 一、环境准备 1、VMware 基于VMware构建Linux虚拟机 是大数据从业者或者IT从业者的必备技能之一也是成本低廉的方案 所以VMware虚拟机方案是必须要学习的。 (1)设置网关 打开VMware虚拟机,点击编辑…...

【第二十一章 SDIO接口(SDIO)】
第二十一章 SDIO接口 目录 第二十一章 SDIO接口(SDIO) 1 SDIO 主要功能 2 SDIO 总线拓扑 3 SDIO 功能描述 3.1 SDIO 适配器 3.2 SDIOAHB 接口 4 卡功能描述 4.1 卡识别模式 4.2 卡复位 4.3 操作电压范围确认 4.4 卡识别过程 4.5 写数据块 4.6 读数据块 4.7 数据流…...

cf2117E
原题链接:https://codeforces.com/contest/2117/problem/E 题目背景: 给定两个数组a,b,可以执行多次以下操作:选择 i (1 < i < n - 1),并设置 或,也可以在执行上述操作前执行一次删除任意 和 。求…...

深入解析C++中的extern关键字:跨文件共享变量与函数的终极指南
🚀 C extern 关键字深度解析:跨文件编程的终极指南 📅 更新时间:2025年6月5日 🏷️ 标签:C | extern关键字 | 多文件编程 | 链接与声明 | 现代C 文章目录 前言🔥一、extern 是什么?&…...

什么是Ansible Jinja2
理解 Ansible Jinja2 模板 Ansible 是一款功能强大的开源自动化工具,可让您无缝地管理和配置系统。Ansible 的一大亮点是它使用 Jinja2 模板,允许您根据变量数据动态生成文件、配置设置和脚本。本文将向您介绍 Ansible 中的 Jinja2 模板,并通…...

2025年渗透测试面试题总结-腾讯[实习]科恩实验室-安全工程师(题目+回答)
安全领域各种资源,学习文档,以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各种好玩的项目及好用的工具,欢迎关注。 目录 腾讯[实习]科恩实验室-安全工程师 一、网络与协议 1. TCP三次握手 2. SYN扫描原理 3. HTTPS证书机制 二…...
Git常用命令完全指南:从入门到精通
Git常用命令完全指南:从入门到精通 一、基础配置命令 1. 用户信息配置 # 设置全局用户名 git config --global user.name "你的名字"# 设置全局邮箱 git config --global user.email "你的邮箱example.com"# 查看所有配置 git config --list…...