标准库与实战
约 60 分钟B2: 包设计与接口
学习 Go 接口的隐式实现、依赖注入模式、包的组织方式
学习目标
- 1.理解 Go 接口与 TS 接口的本质区别
- 2.掌握小接口设计原则
- 3.学会使用接口实现依赖注入
课程内容
本课时将帮助你快速掌握相关知识。以下是示例代码:
main.go
1package main2 3import "fmt"4 5func main() {6 fmt.Println("Hello, Go!")7 8 // Go 的变量声明9 var name string = "TypeScript Developer"10 age := 25 // 短变量声明11 12 fmt.Printf("Name: %s, Age: %d\n", name, age)13}上面的代码演示了 Go 的基本语法,包括包声明、导入和变量声明。 注意第 8 行的短变量声明语法 :=,这是 Go 的特色。
与 TypeScript 对比
example.ts
// TypeScript 版本const name: string = "TypeScript Developer";const age = 25; // 类型推断 console.log(`Name: ${name}, Age: ${age}`);