藉助ai來分析代碼,理解代碼

 

這個庫不錯,學習一下: https://github.com/soheilhy/cmux

 

800行

67 ./buffer.go
179 ./patricia.go
307 ./cmux.go
18 ./doc.go
267 ./matchers.go
838 total

 

ChatGPT prompt: Describe multiplexing connections using cmux in golang, with an example combining grpc and https protocols

https://medium.com/@vtalwar.w/chatgpt-prompt-describe-multiplexing-connections-using-cmux-in-golang-with-an-example-combining-1f5b2a3fa585

 

----------------

 

Certainly! Here's an example to illustrate the usage of the splitPrefix function in Go:

go
package main

import (
	"fmt"
)

func splitPrefix(bss [][]byte) (prefix []byte, rest [][]byte) {
	if len(bss) == 0 || len(bss[0]) == 0 {
		return prefix, bss
	}

	if len(bss) == 1 {
		return bss[0], [][]byte{{}}
	}

	for i := 0; ; i++ {
		var cur byte
		eq := true
		for j, b := range bss {
			if len(b) <= i {
				eq = false
				break
			}

			if j == 0 {
				cur = b[i]
				continue
			}

			if cur != b[i] {
				eq = false
				break
			}
		}

		if !eq {
			break
		}

		prefix = append(prefix, cur)
	}

	rest = make([][]byte, 0, len(bss))
	for _, b := range bss {
		rest = append(rest, b[len(prefix):])
	}

	return prefix, rest
}

func main() {
	// Example usage of splitPrefix

	data := [][]byte{
		[]byte("apple"),
		[]byte("app"),
		[]byte("application"),
	}

	prefix, rest := splitPrefix(data)

	fmt.Println("Common Prefix:", string(prefix))
	fmt.Println("Rest:")
	for _, r := range rest {
		fmt.Println(string(r))
	}
}

In this example, we have a collection of byte slices stored in the data variable. Each byte slice represents a word or a string. We want to find the common prefix among these words and separate it from the rest of the data.

We call the splitPrefix function, passing in the data slice. It returns the prefix slice, which contains the common prefix among the words, and the rest slice, which contains the remaining parts of each word after removing the prefix.

In the main function, we print the common prefix and then iterate over the rest slice to print each word without the common prefix.

When you run this program, the output will be:

 
Common Prefix: app
Rest:
le

In this example, the common prefix among the words "apple", "app", and "application" is "app". The splitPrefix function successfully identifies this common prefix and returns it as the prefix slice. The rest slice contains the remaining parts of each word after removing the prefix, which in this case is "le".

You can use the splitPrefix function in various scenarios where you have a collection of byte slices and you want to identify a common prefix and separate it from the rest of the data, just like in this example.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章