Go 与 C 对照
同一个程序分别用 Go 和 C 编写,取自本课程的课时。
输出与注释
Go 的 fmt 会检查类型化参数,并报告输出中的格式不匹配。C 的 printf 信任可变参数的格式约定;类型不匹配可能导致未定义行为。
Go1package main2import ("fmt")3 4func main(){5fmt.Printf("value=%d\n",7)6}C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10printf("value=%d\n",7);11return 0;12}布尔值与分支
Go 要求条件必须是 bool 类型。C 接受标量真值测试,因此指向空字符串的指针在非 null 时为真;不要把 Go 的 len 语义翻译成指针测试,而应显式检查字符串是否为空。
Go1package main2import ("fmt")3 4func main(){5s:="";fmt.Println(len(s)==0)6}C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10const char *s=""; printf("%s\n",s?"true":"false");11return 0;12}数组需要长度
Go 切片的描述符中包含长度和容量。C 指针两者都不包含。C 指针和长度组成的对类似于借用视图,但 C 不会强制检查其边界或生命周期。
Go1package main2import ("fmt")3 4func main(){5a:=[]int{2,4,6};fmt.Println(len(a))6}C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10int a[]={2,4,6};printf("%zu\n",sizeof a/sizeof a[0]);11return 0;12}函数参数是值
Go 会按值传递值,包括指针和切片描述符。C 也会复制参数。通过复制的指针进行修改会影响指针指向的对象;重新赋值给本地指针不会替换调用方的指针。
Go1package main2import ("fmt")3func change(x int){x=9;_ = x}4func main(){5x:=2;change(x);fmt.Println(x)6}C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8static void change(int n){n=9;(void)n;}9int main(void) {10int x=2;change(x);printf("%d\n",x);11return 0;12}地址与解引用
Go 和 C 都使用 & 和 * 来表示取地址和解引用。Go 会通过垃圾回收让被转义的对象保持存活;当 C 中的自动对象离开作用域时,指针可能会变成悬空指针。
Go1package main2import ("fmt")3 4func main(){5n:=2;p:=&n;*p=5;fmt.Println(n)6}C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10int n=2;int *p=&n;*p=5;printf("%d\n",n);11return 0;12}解析并返回状态结果
Go 的 Atoi 遇到格式错误的输入时会返回错误。C 的 scanf 风格转换可以接受数字前缀;调用方必须决定并检查末尾的字节是否会使整个输入无效。
Go1package main2import ("fmt";"strconv")3 4func main(){5_,err:=strconv.Atoi("12x");fmt.Println(err==nil)6}C1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <stddef.h>5#include <stdbool.h>6#include <limits.h>7#include <errno.h>8 9int main(void) {10const char *s="12x";int ok=*s!=0;for(size_t i=0;s[i];i++)if(s[i]<'0'||s[i]>'9')ok=0;printf("%d\n",ok);11return 0;12}
课程大纲
10 章48 节课1 个项目48 个挑战99 道测验题常见问题
面向 Go 开发者的 C 适合谁学习?
适合已经会写 Go、想学 C 的人。每节课都从你熟悉的 Go 代码出发,展示 C 如何实现同样的事情,所以你可以跳过入门基础。
需要先会 C 吗?
不需要。课程从你的第一个 C 程序开始。你需要掌握 Go 基础:变量、条件、循环、函数和集合。
面向 Go 开发者的 C 有多少节课?
面向 Go 开发者的 C 包含 48 节互动课,你可以按自己的节奏完成。
面向 Go 开发者的 C 包含哪些内容?
本课程分为以下几章:编译与计算, 条件判断与循环, 数组与文本, 函数与接口, and more。
面向 Go 开发者的 C 免费吗?
是的。Coddy 上的每门课程都可以免费开始。你可以直接在浏览器中完成课程,无需下载,也无需注册。