提交 3a6c218e 编写于 作者: _Fighter's avatar _Fighter

2022年1月12日

上级 f47e7e95
此差异已折叠。
...@@ -54,9 +54,12 @@ func euler() { ...@@ -54,9 +54,12 @@ func euler() {
/*强制转换*/ /*强制转换*/
func triangle() { func triangle() {
a, b := 3, 5 a, b := 3, 5
fmt.Println(calcTriangle(a, b))
}
func calcTriangle(a, b int) int {
var c int var c int
c = int(math.Sqrt(float64(a*a + b*b))) c = int(math.Sqrt(float64(a*a + b*b)))
fmt.Println(c) return c
} }
/*常量*/ /*常量*/
......
package main
import "testing"
func TestTriangle(t *testing.T) {
tests := []struct{ a, b, c int }{
{3, 4, 5},
{5, 12, 13},
{8, 15, 17},
{12, 35, 37},
}
for _, tt := range tests {
if actual := calcTriangle(tt.a, tt.b); actual != tt.c {
t.Errorf("calcTriangle(%d, %d) ; got %d; expected %d", tt.a, tt.b, actual, tt.c)
}
}
}
package main
import (
"bufio"
"fmt"
"learngo/functional/fib"
"os"
)
/*
1、 确保调用在函数结束时发生
2、 参数在defer语句时计算
3、defer 列表为后进行出
*/
func tryDefer() {
defer fmt.Println(1)
defer fmt.Println(2)
fmt.Println(3)
for i := 0; i < 100; i++ {
defer fmt.Println(i)
if i == 30 {
panic(" printed too many ")
}
}
}
func writeFile(filename string) {
// 打开一个文件
//file, err := os.Create(filename)
file, err := os.OpenFile(filename, os.O_EXCL|os.O_CREATE, 0666)
// 自定义error
//err = errors.New(" this is a custom error !")
fmt.Printf(" open file error %s \n :", err)
//异常处理
if err != nil {
if pathError, ok := err.(*os.PathError); !ok {
panic(err)
} else {
fmt.Printf("%s, %s, %s \n",
pathError.Op,
pathError.Path,
pathError.Err,
)
}
return
}
//关闭文件
defer file.Close()
writer := bufio.NewWriter(file)
// 写入文件
defer writer.Flush()
f := fib.Fibonacci()
for i := 0; i < 20; i++ {
fmt.Fprintln(writer, f())
}
}
func main() {
writeFile("fib1.txt")
//tryDefer()
}
package filelisting
import (
"io/ioutil"
"net/http"
"os"
"strings"
)
const prefix = "/app/"
type userError string
func (e userError) Error() string {
return e.Message()
}
func (e userError) Message() string {
return string(e)
}
func FileList(writer http.ResponseWriter, request *http.Request) error {
if strings.Index(request.URL.Path, prefix) != 0 {
//return errors.New(" path must start with "+prefix)
return userError(" path must start with " + prefix)
}
// app 获取 app/后面的字符串 后跟文件名
path := request.URL.Path[len("/app/"):]
file, err := os.Open(path)
if err != nil {
//panic(err)
//处理没有文件的错误
/*http.Error(writer,
err.Error(),
http.StatusInternalServerError)
return*/
return err
}
defer file.Close()
all, err := ioutil.ReadAll(file)
if err != nil {
return err
}
writer.Write(all)
return nil
}
package main
import (
"learngo/errhandling/filelistingserver/filelisting"
"log"
"net/http"
"os"
)
// 自定义类型 ,返回 error
type appHandler func(writer http.ResponseWriter, request *http.Request) error
func errWrapper(handler appHandler) func(writer http.ResponseWriter, request *http.Request) {
return func(writer http.ResponseWriter, request *http.Request) {
defer func() {
if r := recover(); r != nil {
log.Printf("panic : %v", r)
http.Error(writer, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
err := handler(writer, request)
if err != nil {
log.Printf("Error handling request : %s ", err.Error())
if userError, ok := err.(userError); ok {
http.Error(writer, userError.Message(), http.StatusBadRequest)
return
}
code := http.StatusOK
switch {
case os.IsNotExist(err):
code = http.StatusNotFound
case os.IsPermission(err):
code = http.StatusForbidden
default:
code = http.StatusInternalServerError
}
http.Error(writer, http.StatusText(code), code)
}
}
}
type userError interface {
error
Message() string
}
func main() {
http.HandleFunc("/", errWrapper(filelisting.FileList))
err := http.ListenAndServe(":9999", nil)
if err != nil {
panic(err)
}
}
package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(i int) int {
sum += i
return sum
}
}
func main() {
a := adder()
for i := 0; i < 10; i++ {
fmt.Printf(" 0 + 1 + ... + %d = %d \n", i, a(i))
}
}
package main
import (
"fmt"
"strings"
)
// 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
func Fibonaccit() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return a
}
}
type intGen func() int
func (g intGen) Read(
p []byte) (n int, err error) {
next := g()
s := fmt.Sprintf("%d\n", next)
// TODO: incorrect if p is too small!
return strings.NewReader(s).Read(p)
}
func main() {
var f intGen = Fibonaccit()
for i := 0; i < 20; i++ {
b := make([]byte, 1)
n, err := f.Read(b)
fmt.Printf("%d bytes read: %q. err = %v\n", n, b, err)
}
}
package fib
// 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
func Fibonacci() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return a
}
}
...@@ -2,13 +2,20 @@ package main ...@@ -2,13 +2,20 @@ package main
import "fmt" import "fmt"
// 优化
var lastOccurrend = make([]int, 0xffff) // 65535
func lengthOfNonRepeatingSubStr(s string) int { func lengthOfNonRepeatingSubStr(s string) int {
lastOccurrend := make(map[rune]int) //lastOccurrend := make(map[rune]int)
for i := range lastOccurrend {
lastOccurrend[i] = -1
}
start := 0 start := 0
maxLength := 0 maxLength := 0
// for i ,ch := range[]byte(s){ byte 修改rune 支持中文件 // for i ,ch := range[]byte(s){ byte 修改rune 支持中文件
for i, ch := range []rune(s) { for i, ch := range []rune(s) {
if lastI, ok := lastOccurrend[ch]; ok && lastI >= start { if lastI := lastOccurrend[ch]; lastI != -1 && lastI >= start {
start = lastOccurrend[ch] + 1 start = lastOccurrend[ch] + 1
} }
if i-start+1 > maxLength { if i-start+1 > maxLength {
...@@ -17,10 +24,10 @@ func lengthOfNonRepeatingSubStr(s string) int { ...@@ -17,10 +24,10 @@ func lengthOfNonRepeatingSubStr(s string) int {
lastOccurrend[ch] = i lastOccurrend[ch] = i
} }
for v, _ := range lastOccurrend { //for v, _ := range lastOccurrend {
fmt.Printf("(%c )", v) // fmt.Printf("(%c )", v)
} //}
fmt.Println() //fmt.Println()
return maxLength return maxLength
} }
......
package main
import "testing"
func TestSubstr(t *testing.T) {
tests := []struct {
s string
ans int
}{
// Normal cases
{"abcabcbb", 3},
{"abcabcbb", 3},
//Edge cases
{"", 0},
{"aaaaaaa", 1},
{"abbabbabbc", 2},
//chinese support
{"这里我测试", 5},
}
for _, tt := range tests {
if actual := lengthOfNonRepeatingSubStr(tt.s); actual != tt.ans {
t.Errorf("got %d for input %s : expected %d ", actual, tt.s, tt.ans)
}
}
}
func BenchmarkDubstr(b *testing.B) {
s := "以html方式查询代码覆盖率报告文件码覆盖率报"
ans := 18
for i := 0; i < 13; i++ {
s = s + s
}
b.Logf("len(s) = %d ", len(s))
//重置时间
b.ResetTimer()
for i := 0; i < b.N; i++ {
actual := lengthOfNonRepeatingSubStr(s)
if actual != ans {
b.Errorf("got %d for input : expected %d ", actual, ans)
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册