Golang面试题解析（四）

31. 算法

"北京天安门最美丽" , "天安门"

``````import (
"fmt"
"strings"
)

func main(){
fmt.Println(Utf8Index("北京天安门最美丽", "天安门"))
fmt.Println(strings.Index("北京天安门最美丽", "男"))
fmt.Println(strings.Index("", "男"))
fmt.Println(Utf8Index("12ws北京天安门最美丽", "天安门"))
}

func Utf8Index(str, substr string) int {
asciiPos := strings.Index(str, substr)
if asciiPos == -1 || asciiPos == 0 {
return asciiPos
}
pos := 0
totalSize := 0
for _, size, err := reader.ReadRune(); err == nil; _, size, err = reader.ReadRune() {
totalSize += size
pos++
// 匹配到
if totalSize == asciiPos {
return pos
}
}
return pos
}``````

32，编程

``````package main

import "sync"

// 实现一个单例

type singleton struct{}

var ins *singleton
var mu sync.Mutex

//懒汉加锁:虽然解决并发的问题，但每次加锁是要付出代价的
func GetIns() *singleton {
mu.Lock()
defer mu.Unlock()

if ins == nil {
ins = &singleton{}
}
return ins
}

//双重锁:避免了每次加锁，提高代码效率
func GetIns1() *singleton {
if ins == nil {
mu.Lock()
defer mu.Unlock()
if ins == nil {
ins = &singleton{}
}
}
return ins
}

//sync.Once实现
var once sync.Once

func GetIns2() *singleton {
once.Do(func() {
ins = &singleton{}
})
return ins
}
``````

33,执行下面的代码发生什么？

``````package main

import (
"fmt"
"time"
)

func main() {
ch := make(chan int, 1000)
go func() {
for i := 0; i < 10; i++ {
ch <- i
}
}()
go func() {
for {
a, ok := <-ch
if !ok {
fmt.Println("close")
return
}
fmt.Println("a: ", a)
}
}()
close(ch)
fmt.Println("ok")
time.Sleep(time.Second * 100)
}
``````

考点:channel

``panic: send on closed channel``

34,执行下面的代码发生什么？

``````import "fmt"

type ConfigOne struct {
Daemon string
}

func (c *ConfigOne) String() string {
return fmt.Sprintf("print: %v", p)
}

func main() {
c := &ConfigOne{}
c.String()
}``````

考点:fmt.Sprintf

``````runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow``````

35，编程题

``````func reverse(x int) (num int) {
for x != 0 {
num = num*10 + x%10
x = x / 10
}
// 使用 math 包中定义好的最大最小值
if num > math.MaxInt32 || num < math.MinInt32 {
return 0
}
return
}
``````

36，编程题

``````type Interval struct {
Start int
End   int
}

func merge(intervals []Interval) []Interval {
if len(intervals) <= 1 {
return intervals
}

sort.Slice(intervals, func(i, j int) bool {
return intervals[i].Start < intervals[j].Start
})

res := make([]Interval, 0)
swap := Interval{}
for k, v := range intervals {
if k == 0 {
swap = v
continue
}
if v.Start <= swap.End {
swap.End = v.End
} else {
res = append(res, swap)
swap = v
}
}
res = append(res, swap)
return res
}``````

37.输出什么？

``````package main

import (
"fmt"
)

func main() {
fmt.Println(len("你好bj!"))
}``````

38.编译并运行如下代码会发生什么？

``````package main

import "fmt"

type Test struct {
Name string
}

var list map[string]Test

func main() {

list = make(map[string]Test)
name := Test{"xiaoming"}
list["name"] = name
list["name"].Name = "Hello"
fmt.Println(list["name"])
}``````

39.ABCD中哪一行存在错误？

``````type S struct {
}

func f(x interface{}) {
}

func g(x *interface{}) {
}

func main() {
s := S{}
p := &s
f(s) //A
g(s) //B
f(p) //C
g(p) //D

}``````

40.编译并运行如下代码会发生什么？

``````package main

import (
"sync"
//"time"
)

const N = 10

var wg = &sync.WaitGroup{}

func main() {

for i := 0; i < N; i++ {
go func(i int) {
println(i)
defer wg.Done()
}(i)
}
wg.Wait()

}``````

考点:WaitGroup

``````for i := 0; i < N; i++ {
go func(i int) {
println(i)
defer wg.Done()
}(i)
}
wg.Wait()``````

附录

https://zhuanlan.zhihu.com/p/35058068?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io

https://stackoverflow.com/questions/42600920/runtime-goroutine-stack-exceeds-1000000000-byte-limit-fatal-error-stack-overf

https://studygolang.com/topics/3853

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

31. 算法

"北京天安门最美丽" , "天安门"

``````import (
"fmt"
"strings"
)

func main(){
fmt.Println(Utf8Index("北京天安门最美丽", "天安门"))
fmt.Println(strings.Index("北京天安门最美丽", "男"))
fmt.Println(strings.Index("", "男"))
fmt.Println(Utf8Index("12ws北京天安门最美丽", "天安门"))
}

func Utf8Index(str, substr string) int {
asciiPos := strings.Index(str, substr)
if asciiPos == -1 || asciiPos == 0 {
return asciiPos
}
pos := 0
totalSize := 0
for _, size, err := reader.ReadRune(); err == nil; _, size, err = reader.ReadRune() {
totalSize += size
pos++
// 匹配到
if totalSize == asciiPos {
return pos
}
}
return pos
}``````

32，编程

``````package main

import "sync"

// 实现一个单例

type singleton struct{}

var ins *singleton
var mu sync.Mutex

//懒汉加锁:虽然解决并发的问题，但每次加锁是要付出代价的
func GetIns() *singleton {
mu.Lock()
defer mu.Unlock()

if ins == nil {
ins = &singleton{}
}
return ins
}

//双重锁:避免了每次加锁，提高代码效率
func GetIns1() *singleton {
if ins == nil {
mu.Lock()
defer mu.Unlock()
if ins == nil {
ins = &singleton{}
}
}
return ins
}

//sync.Once实现
var once sync.Once

func GetIns2() *singleton {
once.Do(func() {
ins = &singleton{}
})
return ins
}
``````

33,执行下面的代码发生什么？

``````package main

import (
"fmt"
"time"
)

func main() {
ch := make(chan int, 1000)
go func() {
for i := 0; i < 10; i++ {
ch <- i
}
}()
go func() {
for {
a, ok := <-ch
if !ok {
fmt.Println("close")
return
}
fmt.Println("a: ", a)
}
}()
close(ch)
fmt.Println("ok")
time.Sleep(time.Second * 100)
}
``````

考点:channel

``panic: send on closed channel``

34,执行下面的代码发生什么？

``````import "fmt"

type ConfigOne struct {
Daemon string
}

func (c *ConfigOne) String() string {
return fmt.Sprintf("print: %v", p)
}

func main() {
c := &ConfigOne{}
c.String()
}``````

考点:fmt.Sprintf

``````runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow``````

35，编程题

``````func reverse(x int) (num int) {
for x != 0 {
num = num*10 + x%10
x = x / 10
}
// 使用 math 包中定义好的最大最小值
if num > math.MaxInt32 || num < math.MinInt32 {
return 0
}
return
}
``````

36，编程题

``````type Interval struct {
Start int
End   int
}

func merge(intervals []Interval) []Interval {
if len(intervals) <= 1 {
return intervals
}

sort.Slice(intervals, func(i, j int) bool {
return intervals[i].Start < intervals[j].Start
})

res := make([]Interval, 0)
swap := Interval{}
for k, v := range intervals {
if k == 0 {
swap = v
continue
}
if v.Start <= swap.End {
swap.End = v.End
} else {
res = append(res, swap)
swap = v
}
}
res = append(res, swap)
return res
}``````

37.输出什么？

``````package main

import (
"fmt"
)

func main() {
fmt.Println(len("你好bj!"))
}``````

38.编译并运行如下代码会发生什么？

``````package main

import "fmt"

type Test struct {
Name string
}

var list map[string]Test

func main() {

list = make(map[string]Test)
name := Test{"xiaoming"}
list["name"] = name
list["name"].Name = "Hello"
fmt.Println(list["name"])
}``````

39.ABCD中哪一行存在错误？

``````type S struct {
}

func f(x interface{}) {
}

func g(x *interface{}) {
}

func main() {
s := S{}
p := &s
f(s) //A
g(s) //B
f(p) //C
g(p) //D

}``````

40.编译并运行如下代码会发生什么？

``````package main

import (
"sync"
//"time"
)

const N = 10

var wg = &sync.WaitGroup{}

func main() {

for i := 0; i < N; i++ {
go func(i int) {
println(i)
defer wg.Done()
}(i)
}
wg.Wait()

}``````

考点:WaitGroup

``````for i := 0; i < N; i++ {
go func(i int) {
println(i)
defer wg.Done()
}(i)
}
wg.Wait()``````

附录

https://zhuanlan.zhihu.com/p/35058068?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io

https://stackoverflow.com/questions/42600920/runtime-goroutine-stack-exceeds-1000000000-byte-limit-fatal-error-stack-overf

https://studygolang.com/topics/3853