Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

干爆!Golang 面试题 #16

Open
RedCrazyGhost opened this issue Mar 10, 2024 · 0 comments
Open

干爆!Golang 面试题 #16

RedCrazyGhost opened this issue Mar 10, 2024 · 0 comments
Labels
Golang fa-brands fa-golang

Comments

@RedCrazyGhost
Copy link
Owner

RedCrazyGhost commented Mar 10, 2024

前言

主要记录在面试中遇到的试题

程序调度

Q1. 多个 defer() 和 return 的执行顺序

A:defer 压入方法栈中,先进后出,return 返回值在所有 defer 执行完成后执行

package main

import "fmt"

func run() int{
	defer (func() {
		fmt.Println(1)
	})()

	defer (func() {
		fmt.Println(2)
	})()

	defer (func() {
		fmt.Println(3)
	})()
	
	return 4
}

func main() {
	fmt.Println(run())
}
3
2
1
4

字符串

Q1. '"` 有什么区别

A:

' " `
int32 string string
字符 字符串 字符串
采用 unicode 编码 会解析字符串中的转义字符(解析转义字符会消耗性能) 不会解析字符串中的转义字符(性能更好)

参考内容:

切片

Q1: 切片的扩容因子是多少?

A:这个涉及到版本会有所不同,最终的内存分配都会想上修正

  • 1.18 之前:
    • cap < 1024 扩容因子为 2
    • cap >= 1024 扩容因子为 1.25
  • 1.18 及其之后:
    • cap < 256 扩容因子为 2
    • cap >= 256 扩容因子 平滑扩容 逐步递减直到 1.25(每次+ 3/4 * 256)
starting cap growth factor
256 2.0
512 1.63
1024 1.44
2048 1.35
4096 1.30

参考内容

Q2: 下方代码的打印结果如何?

package main

import "fmt"

func main() {
        s := make([]int, 5)
        s = append(s, 1, 2, 3)
	fmt.Println(s)
}

A: 切片中会默认存放当前类型的默认值,在其后方追加内容。

[0 0 0 0 0 1 2 3]
@RedCrazyGhost RedCrazyGhost added the Golang fa-brands fa-golang label Mar 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Golang fa-brands fa-golang
Projects
None yet
Development

No branches or pull requests

1 participant